iblog 5

苹果有iphone,我有iblog

导航

[原创]LINQ多数据源连接查询

Posted on 2013-06-24 15:44  cbtech  阅读(1830)  评论(1编辑  收藏  举报

LINQ的连接查询通过join字句实现,但一个join字句一次只能连接2个数据源。其基本语法如下:

var query= from a in list1

                 jion b in list2

                 on a.id equals b.id

                select ……

当有3个或更多的数据源需要连接查询时,当个join字句就不能胜任了。解决办法有2个:一是嵌套查询,二是将连接查询的结果和另外的数据源再次连接查询。第二种方法的实例如下:

数据源:

 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     }

连接查询:

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); 
}