Linq带有条件连接

时间:2011-11-10 18:50:04

标签: c# linq-to-sql

我无法将以下左连接SQL转换为linq:

select  Students.StudentID, StudentAddresses.state
from Students left join Studentaddresses on (Students.StudentID = Studentaddresses.StudentID and StudentAddresses.Active=1)
where (StudentAddresses.Rank =1  or StudentAddresses.StudentID is null)
and Students.StudentID =3

学生可以在学生地址表中拥有零记录或多个记录,但只有一个记录可以是活动的并且等级= 1。

我能够在linq中进行左连接并使其适用于正常情况。但是,如果学生在学生表中有两个非活动记录,我不知道如何使学生记录在最终结果中只出现一次。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

使用Distinct()折叠重复项。

var LeftJoin = (from student in Students
                join address in (from address1 in StudentAddresses where address.Active select address1) 
                on student.StudentID equals address.StudentId
                into JoinedStudentAddress
                from joined in JoinedStudentAddress.DefaultIfEmpty()
                select new                          
                {
                    StudentID = student.StudentID,
                    State = joined != null ? joined.State : null
                }).Distinct();

替代语法

 var LeftJoin = Students.GroupJoin( StudentAddress.Where( a => a.Active ),
                                    s => s.StudentID,
                                    a => a.StudentID,
                                    (s,a) => new { Student = s, Addresses = a } )
                        .SelectMany( j = > j.Addresses.DefaultIfEmpty()
                                     (s,a) => new {
                                                 StudentID = s.Student.StudentID,
                                                 State = a != null ? a.State : null
                                    })
                        .Distinct();

答案 1 :(得分:0)

这将是转换为linq的SQL语句:

var q = from student in Students
        from adress in Studentaddresses.Where(x => student.StudentID == x.StudentID && x.Active).DefaultIfEmpty()
        where (adress.Rank == 1 || adress.StudentID == null) && student.StudentID == 3
        select new                          
        {
           StudentID = student.StudentID,
           State = adress.state
        };