C# LINQ Aggregate的用法小結(jié)
更新時間:2025年07月01日 10:59:09 作者:Xioa.
LINQ的Aggregate方法是一個強大的聚合操作符,用于對序列執(zhí)行累積操作,文中通過示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
LINQ的Aggregate方法是一個強大的聚合操作符,用于對序列執(zhí)行累積操作。
基本語法
public static TResult Aggregate<TSource, TAccumulate, TResult>(
this IEnumerable<TSource> source,
TAccumulate seed,
Func<TAccumulate, TSource, TAccumulate> func,
Func<TAccumulate, TResult> resultSelector
)使用示例
簡單求和
int[] numbers = { 1, 2, 3, 4, 5 };
int sum = numbers.Aggregate((a, b) => a + b);
// 結(jié)果: 15帶初始值的累加
int[] numbers = { 1, 2, 3, 4, 5 };
int sum = numbers.Aggregate(10, (a, b) => a + b);
// 結(jié)果: 25 (10 + 1 + 2 + 3 + 4 + 5)字符串連接
string[] words = { "Hello", "World", "!" };
string result = words.Aggregate((a, b) => a + " " + b);
// 結(jié)果: "Hello World !"復(fù)雜對象處理
var products = new List<Product>
{
new Product { Name = "A", Price = 10 },
new Product { Name = "B", Price = 20 },
new Product { Name = "C", Price = 30 }
};
decimal totalPrice = products.Aggregate(0m,
(sum, product) => sum + product.Price);
// 結(jié)果: 60帶結(jié)果轉(zhuǎn)換的聚合
string[] words = { "apple", "banana", "cherry" };
string result = words.Aggregate(
seed: 0, // 初始值
func: (length, word) => length + word.Length, // 累加每個單詞的長度
resultSelector: total => $"總字符數(shù): {total}" // 轉(zhuǎn)換最終結(jié)果
);
// 結(jié)果: "總字符數(shù): 17"注意事項
性能考慮
- 對于大數(shù)據(jù)集,考慮使用并行處理
- 避免在循環(huán)中使用Aggregate
空序列處理
// 處理空序列
var emptyList = new List<int>();
int result = emptyList.DefaultIfEmpty(0)
.Aggregate((a, b) => a + b);異常處理
try
{
var result = collection.Aggregate((a, b) => a + b);
}
catch (InvalidOperationException)
{
// 處理空序列異常
}Aggregate方法是LINQ中非常靈活的一個方法,可以用于各種復(fù)雜的聚合操作,但使用時需要注意性能和異常處理
到此這篇關(guān)于C# LINQ Aggregate的用法小結(jié)的文章就介紹到這了,更多相關(guān)C# LINQ Aggregate內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Winform開發(fā)中使用下拉列表展示字典數(shù)據(jù)的幾種方式
這篇文章介紹了Winform開發(fā)中使用下拉列表展示字典數(shù)據(jù)的幾種方式,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-09-09

