c# LINQ的使用

xiaoxiao2021-02-28  81

LINQ是类似于sql语言的一种信息查询方法

基本使用:from m in List  //选择要查询的列表名

         where m的条件     //查询条件

         select m          //输出查询结果

例子:

List<int> TESTA = new List<int>() {     10,20,30,40,50,60,70,80,90,100 };

查找50 以上的数字 

var numres = from n in TESTA                             where n > 50                          select n;

LINQ还可以根据类中的属性筛选结果

var numres = from n in 类名                          where n.字段                          select n.字段;

扩展方法:

(1)调用LIst的Where方法:

 var res3 = List名.Where(比较函数);

(2)lambda表达式

 var res4 = List名.Where(a => a.字段l>8);

LINQ的联合查询方法:

var res4 = from m in listA                  from n in listB                  where m.字段 == n.字段  //链接后 会把元素少的列表的内容匹配到元素多的列表上去                  select new {listA = m, listB = n}

扩展方法:

var res = ListA.selectMany(a =>listB, (a,b)=> new{listA = a, listB = B})  //先把两个list进行排列组合拼接在一起

.where(a=>a.listA.字段1 == a.listB.字段2 && 比较条件)

先根据相同字段连结 然后通过比较筛选

排序方法:OrderBy 和ThenBy

.OrderBy(a => a.类名.字段).ThenBy(a => a.类名.字段);

组的使用:

(1)

var res5 = from m in masters  join n in kongfu on m.kongfu equals n.Name  into groups   orderby groups.Count()   select new { kongfu = m, count = groups.Count() };

(2)

  var res6 = from m in masters   group m by m.kongfu    into g    select new { count = g.Count(), key = g.Key };

Any和All的使用

ListA.Any(委托定义 筛选条件)   //只要有一个满足条件 即返回True

ListB.ALL(委托定义 筛选条件)  //全部满足条件才返回True

转载请注明原文地址: https://www.6miu.com/read-19738.html

最新回复(0)