CodeGym /課程 /C# SELF /LINQ 新方法: CountBy 和 AggregateBy

LINQ 新方法: CountBy 和 AggregateBy

C# SELF
等級 32, 課堂 2
開放

1. 前言

如果你以前寫過「經典」LINQ 查詢來分組,比如:


var cityCounts = students.GroupBy(s => s.City)
                         .Select(g => new { City = g.Key, Count = g.Count() });

你一定發現,光是要算每組數量,code 就有點囉唆。.NET 9 推出後,Microsoft 團隊直接幫大家省事,LINQ 多了兩個超常用的新方法:

  • CountBy — 快速依 key 計算元素數量。
  • AggregateBy — 萬用 key 彙總器(不只計數,還能加總、其他都行)。

順帶一提,這些方法是社群敲碗很久才加進來的,很多「進階」LINQ 套件(像 MoreLINQ)早就有類似功能了。

2. CountBy 方法:超簡潔分組計數

說明

CountBy 就是「分組後直接計數」。這方法會回傳一個「key-數量」的集合,這在資料分析超常用:像是熱門城市、各分數學生數、某東西出現頻率等等。

簽名(簡化版):


IEnumerable<(TKey Key, int Count)> CountBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)

實戰應用

範例 1:各城市學生數

假設我們有這個 class:


class Student
{
    public string Name { get; set; }
    public int Grade { get; set; }
    public string City { get; set; }
}

然後我們有一個學生清單:


var students = new List<Student>
{
    new Student { Name = "伊萬", Grade = 5, City = "Neonville" },
    new Student { Name = "安娜", Grade = 4, City = "Los-Santos" },
    new Student { Name = "葉戈爾", Grade = 3, City = "Neonville" },
    new Student { Name = "瑪麗亞", Grade = 5, City = "Rosewater" },
    new Student { Name = "奧列格", Grade = 4, City = "Neonville" }
};

在 .NET 8 或更早你得這樣寫:


var group = students.GroupBy(s => s.City)
                    .Select(g => new { City = g.Key, Count = g.Count() });

foreach (var cityInfo in group)
{
    Console.WriteLine($"{cityInfo.City}: {cityInfo.Count} 位學生");
}

在 .NET 9 只要一行就搞定:


var cityCounts = students.CountBy(s => s.City);
foreach (var (city, count) in cityCounts)
{
    Console.WriteLine($"{city}: {count} 位學生");
}

沒錯,完全不用手動 GroupBy,也不用自己 Count(),超直覺!

範例 2:分數分布

每個系主任都想知道優等生跟普通生各有多少人:


var gradeCounts = students.CountBy(s => s.Grade);

foreach (var (grade, count) in gradeCounts)
{
    Console.WriteLine($"分數 {grade}: {count} 位學生");
}

範例 3:字串中每個字母出現次數

CountBy 不只可以用在物件,也能用在更簡單的東西:


string word = "supercalifragilisticexpialidocious";
var charFrequencies = word.CountBy(ch => ch);

foreach (var (letter, count) in charFrequencies)
{
    Console.WriteLine($"{letter} : {count}");
}

記憶體裡長怎樣(圖解)

Key Count(CountBy 前) Count(用 CountBy)
"Neonville"
3 3
"Rosewater"
1 1
"Los Santos"
1 1

這種寫法讓 code 超好讀,分組時也比較不會出錯。

常見錯誤跟小細節

別忘了 CountBy 回傳的是 tuple (Key, Count),不是匿名型別。有時候語意上沒那麼 fancy,但超直白。另外 Count 的型別不能自己指定,永遠都是 int。

3. AggregateBy 方法:萬用分組彙總

說明

CountBy 是簡單計數,AggregateBy 就是瑞士刀!你想算業績總和、每班最高分、或任何能用 accumulator 表達的東西,AggregateBy 都能搞定。

簽名(大幅簡化):


IEnumerable<(TKey Key, TAccumulate Result)> AggregateBy<TSource, TKey, TAccumulate>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector,
    TAccumulate seed,
    Func<TAccumulate, TSource, TAccumulate> func)
  • keySelector — 要依什麼分組。
  • seed — 累加的初始值。
  • func — 怎麼「累加」結果的 function。

實戰應用

範例 1:各城市分數總和

不用再寫超長 LINQ:


var sums = students.GroupBy(s => s.City)
                   .Select(g => new { City = g.Key, Sum = g.Sum(s => s.Grade) });

你可以這樣寫:


var sums = students.AggregateBy(
    s => s.City, // 依城市分組
    0,           // 初始總和
    (acc, s) => acc + s.Grade // 加上分數
);

foreach (var (city, sum) in sums)
{
    Console.WriteLine($"{city}: 分數總和 = {sum}");
}

範例 2:各城市最高分

想要最大值,只要換個 accumulator:


var maxByCity = students.AggregateBy(
    s => s.City,
    int.MinValue, // 初始值設最小
    (max, s) => Math.Max(max, s.Grade)
);
foreach (var (city, maxGrade) in maxByCity)
{
    Console.WriteLine($"{city}: 最高分 = {maxGrade}");
}

範例 3:把名字串成一行

更新一下學生清單:


var namesByCity = students.AggregateBy(
    s => s.City,
    "", // 初始字串
    (acc, s) => string.IsNullOrEmpty(acc) ? s.Name : acc + ", " + s.Name
);

foreach (var (city, names) in namesByCity)
{
    Console.WriteLine($"{city}: {names}");
}

內部運作圖解


.   {Student, Student, Student, ...}
               |
               |(依 city 分組)
               v
["Neonville"]  ["Rosewater"]  ["Los Santos"]
      |           |               |
      |     (累加)              |
      |___________________________|
            |
            v
{("Neonville", 總和), ("Rosewater", 總和), ...}

跟「舊寫法」對比

以前這種需求都要寫 GroupBy + Select,裡面還要 Sum、Aggregate 或其他 trick。現在 AggregateBy 直接幫你包好,code 超短又超清楚。

實作練習:用在專案裡

我們的學生日記專案,來加個各城市平均分數報表。


// 用 AggregateBy 算平均分數 — 累加總和跟數量,最後算平均
var avgByCity = students.AggregateBy(
    s => s.City,
    (Sum: 0, Count: 0),
    (acc, s) => (acc.Sum + s.Grade, acc.Count + 1)
).Select(x => (x.Key, Average: (double)x.Result.Sum / x.Result.Count));

foreach (var (city, avg) in avgByCity)
{
    Console.WriteLine($"{city}: 平均分數 = {avg:F2}");
}

這裡我們用 tuple 累加總和跟數量,最後用總和除以數量拿到平均。

注意事項跟小陷阱

如果你的 accumulator 是 reference type,記得:AggregateBy 內部同一個 reference 會給那組所有元素用,所以不要去 mutate 物件,不然會影響整組結果。

還有:如果你不只要分組,還要再轉換結果,可以直接接 .Select。記得 seed(初始值)要選語意正確的,不然結果會怪怪的(比如字串不要用 0)。

4. 舊新寫法對比

需求 舊 LINQ 新 LINQ .NET 9
各城市學生數
GroupBy + Select + Count
students.CountBy(s => s.City)
各城市分數總和
GroupBy + Select + Sum
students.AggregateBy(..., 0, ...)
各城市最高分
GroupBy + Select + Max
students.AggregateBy(..., ...)
字串中每個字母出現次數
GroupBy + Select + Count
word.CountBy(ch => ch)

實務上有什麼好處?

像 CountBy 跟 AggregateBy 這種方法,寫統計報表、資料視覺化、做 pivot table 這些超方便。code 變短、超好讀,重點是更穩:不用自己手動分組彙總,邏輯也不容易出錯。

面試 Junior/Middle 時,會 LINQ 新方法代表你有在追 .NET 新功能;在 production 上用,省掉自己造輪子,寫出來的 code 也超容易維護跟閱讀。

2
任務
C# SELF, 等級 32, 課堂 2
上鎖
依城市找出最高分
依城市找出最高分
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION