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

LINQ 集合操作全解析:聚合、合併、自定義 Aggregate

     編輯:關於C#

聚合操作:Count、Sum、Min、Max、Average

// 學生姓名長度 > 4 的數量
int count = students.Count(s => s.Name.Length > 4); // 1 (Cindy)

// 總分
double total = scores.Sum(s => s.Value);

// 最高分
double max = scores.Max(s => s.Value); // 96

// 平均分
double avg = scores.Average(s => s.Value); // 75.23

要求:Sum/Min/Max/Average 要求元素為基本值類型或可空類型;Min/Max 要求實現 IComparable。

集合合併:Union

var allStudents = students.Union(students2); // 不去重,單純合併
// 若需去重:allStudents.Distinct()

Aggregate:最靈活的自定義聚合

簽名:Aggregate<TSource, TAccumulate, TResult>(seed, func, resultSelector)

  • seed:累加器初始值
  • func(acc, item):每個元素如何更新累加器
  • resultSelector(acc):最終轉換為結果

案例 1:字串拼接 (相當於自定義 Sum)

string names = students
    .Select(s => s.Name)
    .Aggregate("Names:", (acc, name) => acc + " " + name, acc => acc + "\n");
// "Names: Andy Bill Cindy Dark\n"

案例 2:按字典序取最大姓名 (相當於自定義 Max)

string maxName = students
    .Select(s => s.Name)
    .Aggregate((a, b) => string.Compare(a, b) > 0 ? a : b); // "Dark"

案例 3:計算平均分並返回 Score 對象 (自定義 Average)

var coll = scores.ToList(); // 需多次用到 Count()
var avgScore = coll.Aggregate(
    new Score { Value = 0 },           // seed
    (acc, s) => new Score { Value = acc.Value + s.Value }, // 累加
    acc => new Score { Value = acc.Value / coll.Count() }   // 最終轉換
).Value; // 75.23

集合操作對延遲執行的影響

操作執行模式說明
Count/Sum/Min/Max/Average立即執行需遍歷全集合得出單一值
Union/Distinct延遲執行迭代時才逐個產生
Aggregate立即執行需完整遍歷累加
ToList/ToArray立即執行物化緩存

效能陷阱與優化

  1. 避免重複遍歷:var list = query.ToList(); var c = list.Count; var s = list.Sum();
  2. 大數據源慎用 Count():改用 Any() 判斷是否為空
  3. Aggregate seed 選擇:引用類型 seed 每次 new 會產生大量垃圾,考慮值類型或可變對象

實用擴展:統計分組 Top N

// 每位學生最高分
var topScores = scores
    .GroupBy(s => s.StudentId)
    .Select(g => g.OrderByDescending(s => s.Value).First());

集合操作是 LINQ 與 SQL 功能對齊的關鍵,靈活運用 Aggregate 更能處理標準聚合無法覆蓋的業務邏輯。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved