var res=from m in masterList where m.level>8 &&m.menpai=="丐帮"select m;(表达式的写法) var res=from m in masterList where m.level>8 select m.name; foreach(var temp in res) { cw(temp) } var res= masterList.Where(Test);//list中的每个元素都会调用where
1.联合查询
var res= from m in masterList from k in kongfuList where m.kongfu==k.name&&k.Power>90//先联合后限制 select new(master=m,kongfu=k);//创建了两个临时对象 做映射 select m;//所学功夫杀伤力>90的武林高手
扩展方法的用法:
var res=masterList.selectMany(m=>kongfuList,(m,k)=>new{master=m,kongfu=k});//做映射
var res=masterList.selectMany(m=>kongfuList,(m,k)=>new{master=m,kongfu=k}).where(x=>x.master.kongfu==x.kongfu.name&&x.kongfu.Power>90);//
2.排序
var res=from m in masterList//设置查询的集合 where m.level>8&&m.menpai="丐帮"//通过&&添加并列的条件 orderby m.Age m.level descending(或者m.level)//按照多个字段排序 select m;//表示m的结果结合返回 扩展方法: var res=masterList.Where(m=>m.level>8&&m.menpai=="丐帮").Orderby(m=>m.Age); var res=masterList.Where(m=>m.level>8&&m.menpai=="丐帮").Orderby(m=>m.Age).Thenby(m=>m.age);
3.join on 集合联合
var res=from m in maseterList join k in kongfuList on m.kongfu equals k.Name where k.Power>90 select new {master=m,kongfu=k};//
4.分组查询(把武林高手按照所学功夫分类)
var res-from k in kongfuList join m in masterList on k.name equals m.kongfu into groups orderby groups.Count() select new{kongfu=k,count=groups.count()};
5.按照自身字段分组group
var res=from m in masterList group m by menpai into g select new {count=g.count(),g.key}//g.key,key表示按照哪个属性分的组
6.量词操作
bool res=masterList.Any(m=>m.menpai=="长流"); bool res=masterList.All(m=>m.menpai="长流");
实践操作:项目中遇到一个问题,需要把一个大的list,根据其中对象的属性再次进行拆分成多个小的list操作如下
public class FeatWithBSM { public IFeature feature { get; set; } public string BSM { get; set; } } public class FeatureCate { public List<FeatWithBSM> features; public string BSM; public double SumArea; public string ZDGN_1; public string ZYSZ_1; public string LZ_1; public string ZXJL_1; } List<FeatWithBSM> featureList= searchFeatures("",layer);//初始化最大的原始的List var group1 = featureList.GroupBy(x => x.BSM).Select(x => new FeatureCate { BSM = x.Key, features = x.ToList() }).ToList();
在GroupBy中的参数x是list中的单个FeatWithBSM,返回值是IEnumerable<IGroup<string,FeatWithBSM>>
在Select中的参数x是IGroup<string,FeatWithBSM> 箭头函数输出的是新的类的实例 FeatureCate