[原創]LINQ多數據源鏈接查詢

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); 
}
相關文章
相關標籤/搜索