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

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

編輯:關於C語言

等效的擴展方法調用實現為:

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

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