// 學生姓名長度 > 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。
var allStudents = students.Union(students2); // 不去重,單純合併
// 若需去重:allStudents.Distinct()
簽名:Aggregate<TSource, TAccumulate, TResult>(seed, func, resultSelector)
seed:累加器初始值func(acc, item):每個元素如何更新累加器resultSelector(acc):最終轉換為結果string names = students
.Select(s => s.Name)
.Aggregate("Names:", (acc, name) => acc + " " + name, acc => acc + "\n");
// "Names: Andy Bill Cindy Dark\n"
string maxName = students
.Select(s => s.Name)
.Aggregate((a, b) => string.Compare(a, b) > 0 ? a : b); // "Dark"
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 | 立即執行 | 物化緩存 |
var list = query.ToList(); var c = list.Count; var s = list.Sum();Any() 判斷是否為空// 每位學生最高分
var topScores = scores
.GroupBy(s => s.StudentId)
.Select(g => g.OrderByDescending(s => s.Value).First());
集合操作是 LINQ 與 SQL 功能對齊的關鍵,靈活運用 Aggregate 更能處理標準聚合無法覆蓋的業務邏輯。