C# LINQ Aggregate 方法详解

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中非常灵活的一个方法,可以用于各种复杂的聚合操作,但使用时需要注意性能和异常处理

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值