等效的擴展方法調用實現為:
var result = DataSource.Scores.GroupBy(score => score.StudentID);
返回類型為:IEnumerable<TResult>
對分組結果進行一些包裝,如包裝為匿名類型。
返回按學號分組學生的成績
var result = from score in DataSource.Scores
group score by score.StudentID into scoreGroup
select new { StudentID = scoreGroup.Key, Group = scoreGroup };
匿名類型中Group為IGrouping<TKey, TSource>類型。
等效的擴展方法調用實現為:
var result = DataSource.Scores.GroupBy(score => score.StudentID,
(key, group) => new { StudentID = key, Group = group });
其他一些重載使用方法類似。
Join
連接操作。
public static IEnumerable<TResult> Join<TOuter, TInner, TKey, TResult>(
this IEnumerable<TOuter> outer,
IEnumerable<TInner> inner,
Func<TOuter, TKey> outerKeySelector,
Func<TInner, TKey> innerKeySelector,
Func<TOuter, TInner, TResult> resultSelector)
從Join方法原型可以看出其使用方法。
內連接
選擇左右兩側集合都含有相對應的元素。
示例:
查詢學生的姓名、學科、成績。
var result = from score in DataSource.Scores
join student in DataSource.Students on score.StudentID equals student.StudentID
join course in DataSource.Courses on score.CourseID equals course.CourseID
select new { StudentName = student.Name, CourseName = course.CourseName, ScoreValue = score.Value };
// result
// { StudentName = Andy, CourseName = C Language, ScoreValue = 78 }
// { StudentName = Andy, CourseName = Biophysics, ScoreValue = 60 }
// ...
// { StudentName = Bill, CourseName = C Language, ScoreValue = 59 }
// { StudentName = Cindy, CourseName = Biophysics, ScoreValue = 60 }
// ...
等效的擴展方法調用實現為:
var result =
DataSource.Scores.Join(
DataSource.Students,
score => score.StudentID,
student => student.StudentID,
(score, student) => new { StudentName = student.StudentID, ScoreValue = score.Value, CourseID = score.CourseID })
.Join(DataSource.Courses,
scostu => scostu.CourseID,
course => course.CourseID,
(scostu, course) => new { StudentName = scostu.StudentName, CourseName = course.CourseName, ScoreValue = scostu.ScoreValue });