LINQ的链接查询经过join字句实现,但一个join字句一次只能链接2个数据源。其基本语法以下:ui
var query= from a in list1spa
jion b in list2code
on a.id equals b.idblog
select ……string
当有3个或更多的数据源须要链接查询时,当个join字句就不能胜任了。解决办法有2个:一是嵌套查询,二是将链接查询的结果和另外的数据源再次链接查询。第二种方法的实例以下:io
数据源:class
1 public class studentInfo 2 { 3 public int sid; 4 public string sname; 5 6 public studentInfo(int x,string y) 7 { 8 sid = x; 9 sname = y; 10 11 } 12 } 13 14 public class studentScore 15 { 16 public int sid; 17 public int smath; 18 19 public studentScore(int x, int y) 20 { 21 sid = x; 22 smath = y; 23 24 25 } 26 } 27 28 29 30 31 32 public class studentDetail 33 { 34 public int sid; 35 public string ssex; 36 37 public studentDetail(int x, string y) 38 { 39 sid = x; 40 ssex = y; 41 42 } 43 }
链接查询:foreach
List<studentInfo> stuinfo = new List<studentInfo>(); List<studentDetail> studetail = new List<studentDetail>(); List<studentScore> stuscore = new List<studentScore>(); stuinfo.Add(new studentInfo(1001,"张1源")); stuinfo.Add(new studentInfo(1002, "张2源")); stuscore.Add(new studentScore(1001,10)); stuscore.Add(new studentScore(1002, 20)); studetail.Add(new studentDetail(1001,"男")); studetail.Add(new studentDetail(1002, "女")); var query = from x in stuinfo join y in studetail on x.sid equals y.sid select new {sid=x.sid,sname=x.sname,ssex=y.ssex }; var query2 = from z in query join k in stuscore on z.sid equals k.sid select new {sid=z.sid,sname=z.sname,ssex=z.ssex,smath=k.smath }; foreach (var t in query2) { listBox1.Items.Add(t.sid+"-"+t.sname+"-"+t.ssex+"-"+t.smath); }