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中非常灵活的一个方法,可以用于各种复杂的聚合操作,但使用时需要注意性能和异常处理
到此这篇关于c# linq aggregate的用法小结的文章就介绍到这了,更多相关c# linq aggregate内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论