C# Enumerable Take
Description
Returns a specified number of contiguous elements from the start of a sequence.
Syntax
public static IEnumerable<TSource> Take<TSource>(
this IEnumerable<TSource> source,
int count
)
Parameters
TSource
- The type of the elements of source.source
- The sequence to return elements from.count
- The number of elements to return.
Example
The following code example demonstrates how to use Take to return elements from the start of a sequence.
/*www .ja v a 2 s .c o m*/
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
public static void Main(String[] argv){
int[] grades = { 59, 82, 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);
}
}
}
The code above generates the following result.