LINQ的Aggregate方法是C#中用于对集合元素执行累积运算的扩展方法,它可以接收一个委托,将集合中的元素依次按照指定规则进行计算,最终得到一个累积结果。该方法适用于需要对集合元素做连续处理的场景,比如数值累加、字符串拼接、复杂对象的累积计算等。

Aggregate方法基础介绍
Aggregate方法有多个重载版本,最常用的是接收一个Func<TSource,TSource,TSource>委托的版本,该委托定义两个输入参数:当前的累积值和当前遍历到的集合元素,返回新的累积值。方法会从集合的第一个元素开始,依次将累积值和下一个元素传入委托执行,直到遍历完所有元素,返回最终的累积结果。
数值求和场景示例
最常见的用法是对数值集合进行求和,下面是对整数数组求和的示例:
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5 };
// 使用Aggregate方法求和,初始累积值为第一个元素1,依次和后面的元素相加
int sum = numbers.Aggregate((currentSum, next) => currentSum + next);
Console.WriteLine($"数组元素总和为:{sum}");
}
}
上述代码中,Aggregate方法首先取数组第一个元素1作为初始累积值,然后依次和2、3、4、5相加,最终得到总和15。如果需要指定初始累积值,可以使用带种子参数的重载版本:
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5 };
// 指定初始累积值为10,再和数组元素累加
int sumWithSeed = numbers.Aggregate(10, (currentSum, next) => currentSum + next);
Console.WriteLine($"初始值为10时的总和为:{sumWithSeed}");
}
}
字符串拼接场景示例
Aggregate方法也可以用于字符串拼接,将集合中的字符串元素合并成一个完整的字符串:
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> words = new List<string> { "Hello", " ", "World", "!", " This", " is", " LINQ" };
// 拼接所有字符串元素
string result = words.Aggregate((currentStr, next) => currentStr + next);
Console.WriteLine($"拼接后的字符串为:{result}");
}
}
执行上述代码后,会将列表中的所有字符串拼接成"Hello World! This is LINQ"。
自定义累积规则示例
Aggregate方法支持自定义复杂的累积规则,比如计算数组中元素的乘积:
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] numbers = { 2, 3, 4 };
// 计算所有元素的乘积
int product = numbers.Aggregate((currentProduct, next) => currentProduct * next);
Console.WriteLine($"数组元素乘积为:{product}");
}
}
还可以结合种子参数和结果转换参数,比如先对数组元素求和,再将结果转换为字符串:
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5 };
// 初始值为0,求和后转换为字符串并添加前缀
string sumString = numbers.Aggregate(0,
(currentSum, next) => currentSum + next,
total => $"总和为:{total}");
Console.WriteLine(sumString);
}
}
使用注意事项
- 如果集合为空且没有指定种子值,调用Aggregate方法会抛出InvalidOperationException异常,使用前需要确认集合不为空或者指定初始种子值。
- 委托中不要修改原始集合的元素,避免产生不可预期的结果。
- 对于简单的求和、最大值、最小值运算,也可以使用Sum、Max、Min等更语义化的LINQ方法,Aggregate更适合复杂的自定义累积场景。
C#LINQ_Aggregate字符串拼接数值计算数组处理修改时间:2026-06-13 05:15:12