1、OfType<TResult>(IEnumerable) 方法只返回这些元素在 source 均可转换为类型 TResult。 若要改为收到的异常,如果元素不能转换为键入TResult, ,使用 Cast<TResult>(IEnumerable)。
System.Collections.ArrayList fruits = new System.Collections.ArrayList(4);
fruits.Add("Mango");
fruits.Add("Orange");
fruits.Add("Apple");
fruits.Add(3.0);
fruits.Add("Banana");
// Apply OfType() to the ArrayList.
IEnumerable<string> query1 = fruits.OfType<string>();
Console.WriteLine("Elements of type 'string' are:");
foreach (string fruit in query1)
{
Console.WriteLine(fruit);
}
// The following query shows that the standard query operators such as
// Where() can be applied to the ArrayList type after calling OfType().
IEnumerable<string> query2 =
fruits.OfType<string>().Where(fruit => fruit.ToLower().Contains("n"));
Console.WriteLine("\nThe following strings contain 'n':");
foreach (string fruit in query2)
{
Console.WriteLine(fruit);
}
// This code produces the following output:
//
// Elements of type 'string' are:
// Mango
// Orange
// Apple
// Banana
//
// The following strings contain 'n':
// Mango
// Orange
// Banana
2. public static IEnumerable<TSource> Take<TSource>(this IEnumerable<TSource> source, int count);
从序列的开头返回指定的数量的连续元素。
int[] arr = { 3423, 35, 456, 9, 8, 7, 21 };
var result = arr.OrderByDescending(x => x.ToString().Length) //取最长的
.Take(3); // 取出序列中的前三位