当前位置:首页 > Windows程序 > 正文

C# LINQ详解(一)

2021-03-26 Windows程序

LINQ基础介绍 

         .NET,任何数据结构都是由在mscorlib.dllSystem.Collections.Generic命名空间下的Ienumerable<T>接口得到的. 映射可以访问所有的定义在System.Core.dllSystem.Linq命名空间下的枚举类.这个枚举类是定义在System.Core.dllSystem.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 

那么来让我们看一个关于WhereSelect的例子. 

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