知识点总结:Linq和Lambda
基本语法:
Linq:var result=from t in table order by sort ascending/descending select t;
Lambda:var result=table.OrderBy/OrderByDescending(a => a.sort).
1.获取全部记录
Linq:var result =from t in table select t;
Lambda:var result=table.select(t=>new{t.Id,t.Name});
2.获取其中某一字段
Linq:var names=from t in table select t.name;
Lambda:var result=table.select(t=>new{t.Id});
3.获取其中多个字段
Linq:var idnames=from t in table select new{t.id,t.name};
Lambda:var result=table.select(t=>new{t.Id,t.Name});
4.去重
Linq:var names= (from t in table select t.name).Distinct();
Lambda:var names=table.Where((x,i)=>table.FindIndex(z=>z.Name== x.Name) == i)
5.内连接(join | inner join)
Linq:var query=from a in table1 join b in table2 on a.Id equals b.MainId select new {Id=a.Id,MId=b.Id}
Lambda:var query=table1.Join(table2,a=>a.Id,b=>b.Id,(a,b)=>new{Id=a.Id,Mid=b.Id})
6.左连接(left join | left outer join)
Linq:var query=from a in table1 join b in table2 on a.Id equals b.MainId into temp from tt in temp.DefaultIfEmpty select new {Id=a.Id,MId=tt==null?"":tt.Id}
Lambda:var query=table1.GroupJoin(table2,a=>a.Id,b=>b.Id,(a,Grp)=>new{a=a,Grp=Grp}).selectMany(temp0=>temp0.Grp.DefaultIfEmpty(),(temp0,grp)=>new{Id=temp0.a.Id,Mid=(grp==null)?"":grp.Id})
右连接表位置反一下即可