Linq常用查询运算符

jopen 8年前

Linq一共包含五十几个查询运算符,常用的根据类型来区分一共有5类左右,这五类里面一些事在项目查询中经常用到的。不过linq运算符的命名十分规范,基本从字面意思就能猜测出来是干嘛用的,下面我们挑选一些常用的来介绍一下。根据分类我们能分成下面4种类型:

1.返回IEnumerable<T>类型的

1.1 Where:主要用于对于序列的筛选,跟在sql中对数据筛选用法是一样的

1 int[] array = { 1, 3, 5, 7, 2 };  2 var query = array.Where(p => p >= 2); //输出 3,5,7,2

1.2 OfType:这个也用于筛选数据,跟where不同之处在于是对某一类型的数据筛选,根据指定类型对IEnumerable元素的筛选

1 List<object> list = new List<object>();  2 list.Add("Power");  3 list.Add(1);  4 list.Add(DateTime.Now);    5 var query = list.OfType<string>().Where(p => p.StartsWith("P")); //输出   Power 

1.3 Cast:定义在IEnumerable上,用于将非泛型的序列转成泛型序列,当转换不成功的时候,则会抛出异常

1 ArrayList al = new ArrayList();   2 al.Add(100);   3 al.Add(200);  4 al.Add("df"); //抛出System.InvalidCastException异常

1.4 OrderBy,ThenBy,OrderByDescending,ThenByDescending:这几个就是排序,排序,排序。唯一要注意的事情是ThenBy是在IOrderedEnumerable<T>上面定义的拓展方法,因为不能直接在IEnumerable<T>上调用,ThenBy的调用只能排在OrderBy之后

1 List<Product> list2 = new List<Product>();  2 list2.Add(new Product() {Index = 1,value = 2});  3 list2.Add(new Product() { Index = 12 value = 22 });  4 list2.OrderBy(p => p.Index).ThenBy(p => p.value);

1.5 Select:实现了投影操作,可以在其内对对象类型进行转换。例如在select出来的对象中,将其转换成我们所需要的类型

1 list2.Select(p=>new Product {Index = p.Index});//新建了一个product对象

1.6 Take,Skip:skip是跳过几个元素,take是取几个元素,这两个东西用于分页,例如我们想跳过前面十行的数据,取后面十行的数据

1 var q = list.Skip(10).Take(10);

1.7 TakeWhile(),SkipWhile():

TakeWhile在遇到不符合条件的元素的时候返回前面找到符合条件的元素

1 int[] arr = {1, 4, 8, 2, 3,1};  2 var query1 = arr.TakeWhile(x => x <= 3); //输出 1 

SkipWhile会一直跳过符合条件的元素,直到遇到第一个不符合条件的元素,然后取该元素后面的所有元素

1 var query2 = arr.SkipWhile(x => x <= 3);//输出  4  8 2 3 1

1.8 Reverse()用于将序列中的元素逆序排列

1.9 DefaultIfEmpty()当序列为空的时候,DefaultIfEmpty会添加一个默认值或者指定值,这个在做left join或right join中比较好用,当为空值的时候,我们可以指定他的值

1 int[] arr = {};  2 var query2 = arr.DefaultIfEmpty();//输出  0

1.10 Distinct()主要用于去重复序列

1 int[] arr = {1, 2, 3, 3};  2 var query2 = arr.Distinct();  3 query2.ToList().ForEach(p=> Console.Write(p));//输出 1  2  3 

Int类型能够实现去重复的原因是Int类型继承了IComparable,当假如我们想对一个类的一个字段进行去重复,我们可以调用Distinct的一个重载方法,传递继承于IEqualityComparer<T>的Class

 1 public class ProductComparer:IEqualityComparer<Product>   2 {   3   public bool Equals(Product a, Product b)   4    {   5      return a.Index == b.Index;   6    }   7    8    public int GetHashCode(Product obj)   9    {  10      return obj.Index;  11    }  12 }  13   14 public class Product  15 {  16    public int Index { get; set; }  17 }  18   19    20   21 Product[] array = new[]{  23                 new Product() {Index = 1},  24                 new Product() {Index = 2},  25                 new Product() {Index = 2},  26                 new Product() {Index = 3}  27             };  28    29   30 ProductComparer pc = new ProductComparer();  31 var query2 = array.Distinct(pc); //输出  1   2   3

1.11 GroupBy:在SQL中,group by只能跟聚合函数一起搭配使用,但在linq中,groupby出来的东西可以是一个树形结构

 1 List<Product> list = new List<Product>()   2 {   3     new Product() {Index = 1,Value = 1},   4     new Product() {Index = 2,Value = 2},   5     new Product() {Index = 2,Value = 3},   6     new Product() {Index = 3,Value = 3},   7     new Product() {Index = 4,Value = 5},   8 };   9   10 var query2 = list.GroupBy(p => p.Index).ToList();  11   12 foreach (var item in query2)  13 {  14     Console.Write(item.Key+"-");  15     foreach (var product in item)  16     {  17         Console.Write(product.Value);  18         Console.WriteLine( );  19     }  20 }   //输出   1-1  2-2 3   3-3  4-5        

1.12 Intersect(),Except():Intersect是返回两个序列中相同元素构成的序列,Except则相反

1 int[] arr1 = {1, 2, 3};  2 int[] arr2 = { 2, 5, 6 };  3 var query2 = arr1.Intersect(arr2); //输出  2

1.13  Concat(),Union():concat用于连接两个序列,union也是连接两个序列,但是会剔除相同的项目

1.14 Zip():将两个序列中index相同的元素,组成一个新的元素,长度以短的为准

1 int[] arr = {1, 2, 3, 4};  2 string[] arr2 = {"一", "二", "三", "四", "五"};  3 var query = arr.Zip(arr2, (x, y) => string.Format("{0},{1}", x, y));  4 //输出  1,一  2,二   3,三  4,四

2.返回其他序列类型

ToArray,ToList,ToDictionary,ToLookUp这几个都是将IEnumerable<T>转换成相应类型,就跟平常Tolist一样,没有延迟加载,立即返回。

3.返回序列中的元素

3.1 ElementAt(),ElementAtOrDefault():ElementAt(index)返回下标值为index的元素,不存在的话抛出异常,用ElementAtOrDefault这个返回该类型的默认值来解决异常情况

3.2 First(),FirstOrDefault():First 返回满足条件的第一个序列元素,不存在的话抛出异常,用FirstOrDefault这个返回该类型的默认值来解决异常情况

3.3 Last(),LastOrDefault():Last返回满足条件的最后一个序列元素,不存在的话抛出异常,用LastOrDefault这个返回该类型的默认值来解决异常情况

3.4 Single(),SingleOrDefault():Single跟上面几个有点不一样的地方,它要求序列中有且仅有一个满足条件的项,当大于一项的时候,会抛出异常。SingleOrDefault用于当查询结果为0项时,返回类型默认值。

4.返回标量值

4.1 Count(),LongCount(),Max(),Min(),Average(),Sum():这几个估计大家都非常熟悉了,凭借字面意思就能知道大概了,我们直接来看例子:

 1 int[] arr = {1, 2, 3, 4};   2 int query1 = arr.Count();   3 Console.WriteLine(query1);  //输出 4   4    5 int query2 = arr.Max();   6 Console.WriteLine(query2);//输出 4   7    8 int query3 = arr.Min();   9 Console.WriteLine(query3); //输出 1  10   11 double query4 = arr.Average();  12 Console.WriteLine(query4); //输出 2.5  13   14 int sum = arr.Sum();  15 Console.WriteLine(sum);//输出 10

4.2 Aggregate():返回自定义的聚合,例如每个元素乘2,再相加

1 int sum2 = arr.Aggregate(0, (total, x) => total + (x*2));  2 Console.WriteLine(  sum2);//输出20

4.3 Contains(),Any(),All(),SequenceEqual()

Contains:判断某一元素是否在存在序列中

Any:判断序列中是否存在满足表达式的元素,只要有一个元素满足,返回True。我们经常会判断某一list不为空时,用list.count!=0,这样是比较浪费性能因为会去统计该list全部个数,当我们用any的时候,只要判断第一个元素即可

All:判断序列中是否全部元素都满足表达式,只要一个不满足,则返回fasle

SequenceEqual:用于逐项比较两个序列,当两个序列中元素数目相同,并且元素位置一样,则返回true,否则false

完结

感谢大家观看,祝大家2016年快乐!

来自: http://www.cnblogs.com/powerdk/p/5093455.html