在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);
}
这是测试,没有真实的去读数据库