程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> Linq學習(6) Group & Join(3)

Linq學習(6) Group & Join(3)

編輯:關於C語言

左外連接

當右側的連接的右側沒有左側對應的元素時,內連接會忽略左側元素。要想保留左側元素,可以使用做外連接。右側被置為默認值,如:引用類型被置為空。

示例:

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 }));

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved