Enumerable.Take 方法

定义

重载

Take<TSource>(IEnumerable<TSource>, Int32)

从序列的开头返回指定数量的相邻元素。

Take<TSource>(IEnumerable<TSource>, Range)

从序列中返回指定范围的连续元素。

Take<TSource>(IEnumerable<TSource>, Int32)

Source:
Take.cs
Source:
Take.cs
Source:
Take.cs

从序列的开头返回指定数量的相邻元素。

C#
public static System.Collections.Generic.IEnumerable<TSource> Take<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, int count);

类型参数

TSource

source 的元素类型。

参数

source
IEnumerable<TSource>

要从其返回元素的序列。

count
Int32

要返回的元素数量。

返回

IEnumerable<TSource>

一个 IEnumerable<T>,包含输入序列开头的指定数量的元素。

例外

sourcenull

示例

下面的代码示例演示如何使用 Take 从序列的开头返回元素。

C#
int[] grades = { 59, 82, 70, 56, 92, 98, 85 };

IEnumerable<int> topThreeGrades =
    grades.OrderByDescending(grade => grade).Take(3);

Console.WriteLine("The top three grades are:");
foreach (int grade in topThreeGrades)
{
    Console.WriteLine(grade);
}
/*
 This code produces the following output:

 The top three grades are:
 98
 92
 85
*/

注解

此方法通过使用延迟执行来实现。 即时返回值是一个对象,用于存储执行操作所需的所有信息。 在通过直接调用GetEnumerator其方法或在 C# For Eachforeach Visual Basic 中使用 来枚举对象之前,不会执行此方法表示的查询。

Take 枚举 source 并生成元素,直到 count 元素已生成或 source 不包含更多元素。 如果 count 超出 中的 source元素数,则返回 的所有元素 source

如果 count 小于或等于零, source 则不枚举 ,并返回空 IEnumerable<T>

TakeSkip 方法是功能补充。 给定一个集合序列 coll 和一个整数 n,将 和 的结果 coll.Take(n) 连接在一 coll.Skip(n) 起,生成与 相同的序列 coll

在 Visual Basic 查询表达式语法中, Take 子句转换为 的调用 Take

另请参阅

适用于

.NET 9 和其他版本
产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

Take<TSource>(IEnumerable<TSource>, Range)

Source:
Take.cs
Source:
Take.cs
Source:
Take.cs

从序列中返回指定范围的连续元素。

C#
public static System.Collections.Generic.IEnumerable<TSource> Take<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, Range range);

类型参数

TSource

source 的元素类型。

参数

source
IEnumerable<TSource>

要从其返回元素的序列。

range
Range

要返回的元素范围,它具有序列开头或结尾的开始和结束索引。

返回

IEnumerable<TSource>

一个 IEnumerable<T> ,它包含序列中的 source 指定元素范围。

例外

sourcenull

注解

此方法通过使用延迟执行来实现。 即时返回值是一个对象,用于存储执行操作所需的所有信息。 在通过直接调用GetEnumerator其方法或在 C# For Eachforeach Visual Basic 中使用 来枚举对象之前,不会执行此方法表示的查询。

Take 枚举 source 并生成其索引属于指定的 range的元素。

适用于

.NET 9 和其他版本
产品 版本
.NET 6, 7, 8, 9