左外連接
當右側的連接的右側沒有左側對應的元素時,內連接會忽略左側元素。要想保留左側元素,可以使用做外連接。右側被置為默認值,如:引用類型被置為空。
示例:
var result =
from student in DataSource.Students2
join score in DataSource.Scores on student.StudentID equals score.StudentID into Scores
from score in Scores.DefaultIfEmpty()
select new { student = student, score = score == default(Score) ? 0 : score.Value };
// result:
// { student = Student ID:5,Student Name:Erik, score = 78 }
// { student = Student ID:6,Student Name:Frank, score = 0 }
等效的擴展方法調用實現為:
var result =
DataSource.Students2.GroupJoin(
DataSource.Scores,
student => student.StudentID,
score => score.StudentID,
(student, Scores) => new { student = student, Scores = Scores })
.SelectMany(group => group.Scores.DefaultIfEmpty(),
(group, score) => new { student = group.student, score = (score == null) ? 0.0 : score.Value });
笛卡爾積
集合中的元素交錯連接。
示例:統計學生課程成績時的模板。
var result = from student in DataSource.Students
from course in DataSource.Courses
select new { StudentName = student.Name, CourseName = course.CourseName, ScoreValue = (double?)null };
// result:
// { StudentName = Andy, CourseName = C Language, ScoreValue = }
// { StudentName = Andy, CourseName = Biophysics, ScoreValue = }
// ...
// { StudentName = Bill, CourseName = C Language, ScoreValue = }
// ...
// { StudentName = Cindy, CourseName = Fundamentals of Compiling, ScoreValue = }
// ...
等效的擴展方法調用實現為:
var result = DataSource.Students.SelectMany(
student => DataSource.Courses
.Select(
course =>
new { StudentName = student.Name, CourseName = course.CourseName, ScoreValue = (double?)null }));