Ngôn ngữ LINQ - Toán tử Left Join
Toán tử Left Join
Sử dụng Left Join để hiển thị Student theo từng Standard. Hiển thị tên Standard ngay cả khi không có Student nào được gán cho Standard đó.
var studentsGroup = from stad in standardList
join s in studentList
on stad.StandardID equals s.StandardID
into sg
select new
{
StandardName = stad.StandardName,
Students = sg
};
foreach (var group in studentsGroup)
{
Console.WriteLine(group.StandardName);
group.Students.ToList().ForEach(st => Console.WriteLine(st.StudentName));
}
Đây là kết quả khi biên dịch và thực thi:
Standard 1
John
Steve
Standard 2
Bill
Ram
Standard 3
Trong ví dụ sau chúng tôi trả về danh sách bao gồm StudentName và StandardName tương ứng:
var studentsWithStandard = from stad in standardList
join s in studentList
on stad.StandardID equals s.StandardID
into sg
from std_grp in sg
orderby stad.StandardName, std_grp.StudentName
select new
{
StudentName = std_grp.StudentName,
StandardName = stad.StandardName
};
foreach (var group in studentsWithStandard)
{
Console.WriteLine("{0} is in {1}", group.StudentName, group.StandardName);
}
Đây là kết quả khi biên dịch và thực thi:
John is in Standard 1
Steve is in Standard 1
Bill is in Standard 2
Ram is in Standard 2