LINQ的Aggregate方法是一个强大的聚合操作符,用于对序列执行累积操作。
基本语法
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);
// 结果: 15
带初始值的累加
int[] numbers = { 1, 2, 3, 4, 5 };
int sum = numbers.Aggregate(10, (a, b) => a + b);
// 结果: 25 (10 + 1 + 2 + 3 + 4 + 5)
字符串连接
string[] words = { "Hello", "World", "!" };
string result = words.Aggregate((a, b) => a + " " + b);
// 结果: "Hello World !"
复杂对象处理
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);
// 结果: 60
带结果转换的聚合
string[] words = { "apple", "banana", "cherry" };
string result = words.Aggregate(
seed: 0, // 初始值
func: (length, word) => length + word.Length, // 累加每个单词的长度
resultSelector: total => $"总字符数: {total}" // 转换最终结果
);
// 结果: "总字符数: 17"
注意事项
性能考虑
- 对于大数据集,考虑使用并行处理
- 避免在循环中使用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中非常灵活的一个方法,可以用于各种复杂的聚合操作,但使用时需要注意性能和异常处理