C# LINQ详解(一)
LINQ基础介绍
在.NET中,任何数据结构都是由在mscorlib.dll中System.Collections.Generic命名空间下的Ienumerable<T>接口得到的. 映射可以访问所有的定义在System.Core.dll中System.Linq命名空间下的枚举类.这个枚举类是定义在System.Core.dll中System.Linq命名空间下的一个静态非可继承类.这个枚举类的定义如下:
.class public abstract auto ansi sealed beforefieldinit System.Linq.Enumerable extends [mscorlib]System.Object
这个静态枚举类是对Ienumerable<T>接口中不同扩展方法的一个封装.例如下面的例子:
public static bool Contains<TSource>( this IEnumerable<TSource> source, TSource value) { /* code removed*/} public static int Count<TSource>( this IEnumerable<TSource> source) { /* code removed*/} public static IEnumerable<TSource> Distinct<TSource>( this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer) { /* code removed*/} // and many more
扩展方法介绍
Where and Select
Where 和Select是两个定义在Ienumerable<TSource>接口中非常重要的方法.它们的定义如下:
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate)
所以任何来源于Ienumerable<TSource>接口的数据结构都能访问这个方法,例如List<T>类.List<T>类实现了Ienumerable<T>接口,它的定义如下:
public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, Ienumerable
那么来让我们看一个关于Where和Select的例子.
1 using System; 2 3 using System.Collections; 4 5 using System.Collections.Generic; 6 7 using System.Linq; 8 9 10 11 namespace Chapter_5 12 13 { 14 15 class Program 16 17 { 18 19 static void Main(string[] args) 20 21 { 22 23 IList<string> numbers = new List<string>() 24 25 { 26 27 "One", "Two", "Three", "Four", 28 29 "Five", "Six", "Seven" 30 31 }; 32 33 34 35 var numbersLengthThree = 36 37 numbers.Where(x => x.Length == 3).Select(x => x).ToList(); 38 39 40 41 numbersLengthThree.ForEach(x => Console.WriteLine(x)); 42 43 } 44 45 } 46 47 }
上面的代码会产生一个string类型的列表(列表中是数字)存储在List<string>中,上面的程序会找出在这些项中字符总数是3的并且将结果存储到另外一个新的列表中.最后在控制台中打印出这些数字.这个程序输出的结果如下:
One
Two
Six
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/67995.html