Linq的join后面跟多个条件

在linq中join后面有时候需要跟多个条件。但是它限定了一个on后面只能有一个equals。

所以我们用匿名类来实现。


from s in lstA

join b in lstB on new {s.ID,s.a_Name}equals new {b.ID,b.b_Name} select new {};

这样就解决了join后面跟多个条件。但是他也是有条件限定的,比如,数据类型必须一样,也就是a的ID是int类型,a_Name是字符串类型,那么b的ID也必须是int类型(及时是int?类型也不行),b_Name也必须是字符串类型。

其实还有一种方法可以实现

data = (from a in lstClassOneStu
                    join b in lstClassTwoStu on a.Name equals b.Name into other
                    from s in other where s.Age == a.Age
                    select new Student() { Name = a.Name, Age = a.Age, Gender = a.Gender }).ToList();

当然,我还是喜欢第一种,当用sql server看sql语句的时候,其实就是普通sql语句一样,在on后面跟了2个条件

下面是全部代码

List<Student> lstClassOneStu = new List<Student>() {
                new Student(){ ID = 1, Name = "曹操", Age = 30, Gender = true},
                new Student(){ ID = 2, Name = "刘备", Age = 32, Gender = true},
                new Student(){ ID = 3, Name = "关羽", Age = 33, Gender = true},
                new Student(){ ID = 4, Name = "张飞", Age = 34, Gender = true},
                new Student(){ ID = 5, Name = "赵云", Age = 35, Gender = true}
            };
            List<Student> lstClassTwoStu = new List<Student>() {
                new Student(){ ID = 6, Name = "诸葛亮", Age = 31, Gender = true},
                new Student(){ ID = 7, Name = "马超", Age = 32, Gender = true},
                new Student(){ ID = 8, Name = "黄忠", Age = 38, Gender = true},
                new Student(){ ID = 9, Name = "吕布", Age = 39, Gender = true},
                new Student(){ ID = 10, Name = "赵云", Age = 35, Gender = false}
            };


            List<Student> data = (from a in lstClassOneStu
                                  join b in lstClassTwoStu on new { a.Name, a.Age } equals new { b.Name, b.Age }
                                  select new Student() { Name = a.Name, Age = a.Age, Gender = a.Gender }).ToList();
            data = (from a in lstClassOneStu
                    join b in lstClassTwoStu on a.Name equals b.Name into other
                    from s in other where s.Age == a.Age
                    select new Student() { Name = a.Name, Age = a.Age, Gender = a.Gender }).ToList();
            for (int i = 0; i < data.Count; i++)
            {
                Response.Write(data[i].Name + "," + data[i].Age + "," + data[i].Gender);
            }

这是测试,没有真实的去读数据库

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值