GroupBy 一個或多個欄位
讓我們假設我們有一些電影模型:
public class Film {
public string Title { get; set; }
public string Category { get; set; }
public int Year { get; set; }
}
分類屬性:
foreach (var grp in films.GroupBy(f => f.Category)) {
var groupCategory = grp.Key;
var numberOfFilmsInCategory = grp.Count();
}
按類別和年份分組:
foreach (var grp in films.GroupBy(f => new { Category = f.Category, Year = f.Year })) {
var groupCategory = grp.Key.Category;
var groupYear = grp.Key.Year;
var numberOfFilmsInCategory = grp.Count();
}