近一段时间抽空看了一下Linq的知识,学习了一下,也分享给大家,以后使用也方便,用过Linq的程序员可能都感觉到得到,Linq和sql语法简直就一样。所有会SQl的学习LInq就很容易了。
废话少说,首先我们构造一个数据源方便说明代码
Student[] strAry = { new Student("张三","男",20), new Student("张20","女",20), new Student("张一","男",15), new Student("张花","女",10), new Student("张美丽","女",20), new Student("张坏","男",18), new Student("张蓝蓝","女",20), };
1.普通查询语法from a.....in 集合 where .....select a 如果需要对集合进行简单的分组 为 from a in 集合 where 条件 group a by a.属性 排序字段
var query1 = from st in strAry group st by st.strSex; foreach (var grp in query1) { System.Console.WriteLine(grp.Key); foreach (var val in grp) { System.Console.WriteLine("\t{0}", val); } }
var query2 = from st in strAry group st by st.intAge into stuGrp orderby stuGrp.Key descending select stuGrp; foreach (var stg in query2) { System.Console.WriteLine("{0}岁学生:", stg.Key); foreach (var st in stg) { System.Console.WriteLine("\t{0}", st); } }
2,使用linq同时查询两个集合,其中一个集是另一集合的属性 这里可以使用嵌套查询
Student[] strAry2 = { new Student("张三","男",20,new List<Socre>{new Socre("语文",120),new Socre("数学",60),new Socre("英语",55)}), new Student("张一","男",15,new List<Socre>{new Socre("语文",50),new Socre("数学",50),new Socre("英语",90)}), new Student("张花","女",10,new List<Socre>{new Socre("语文",80),new Socre("数学",60),new Socre("英语",88)}), new Student("张美丽","女",20,new List<Socre>{new Socre("语文",30),new Socre("数学",40),new Socre("英语",80)}), new Student("张坏","男",18,new List<Socre>{new Socre("语文",100),new Socre("数学",60),new Socre("英语",60)}), new Student("张蓝蓝","女",20,new List<Socre>{new Socre("语文",90),new Socre("数学",30),new Socre("英语",86)}), }; var query3 = from str in strAry2 from strc in str.Socres where strc.dblscore > 60 group strc by str.strName;//group 后面的句子是分组形成的数据项 foreach (var stg in query3) { System.Console.WriteLine(stg.Key); foreach (var st in stg) { System.Console.WriteLine("\t{0}", st); } }