首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

LINQ 學習筆記 (六) Group 與 Join 進階 (三) 左外部聯接與笛卡兒積

     編輯:關於C語言

左外部聯接

內部聯接會忽略無對應內部元素的外部元素。左外部聯接保留所有外部元素,無對應時內部元素為預設值(參考型別為 null)。

查詢語法實現

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 };
/* 結果:
{ student = Student ID:5, Name:Erik, score = 78 }
{ student = Student ID:6, 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 };

// 等價方法語法
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