c# aggregate使用

Aggregate 方法是 LINQ 中的一个强大工具,用于对序列应用累加器函数。它可以简化许多聚合运算。

示例:求和

int[] nums = { 1, 2, 3, 4, 5 };

int sum = nums.Aggregate((a, b) => a + b);

Console.WriteLine(sum); // 输出 15

用法

  1. 基本用法

Aggregate<TSource>(IEnumerable<TSource>, Func<TSource, TSource, TSource>) 对序列应用累加器函数。

示例:字符串连接

string[] words = { "Hello", "world" };

string sentence = words.Aggregate((a, b) => a + " " + b);

Console.WriteLine(sentence); // 输出 "Hello world"

  1. 带种子值的用法

Aggregate<TSource, TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate, TSource, TAccumulate>) 使用指定的种子值作为累加器初始值。

示例:计算偶数个数

int[] numbers = { 1, 2, 3, 4, 5 };

int evenCount = numbers.Aggregate(0, (count, n) => n % 2 == 0 ? count + 1 : count);

Console.WriteLine(evenCount); // 输出 2

  1. 带结果选择器的用法

Aggregate<TSource, TAccumulate, TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate, TSource, TAccumulate>, Func<TAccumulate, TResult>) 使用指定的函数选择结果值。

示例:查找最长单词并转换为大写

string[] fruits = { "apple", "banana", "cherry" };

string longestFruit = fruits.Aggregate("",

(longest, next) => next.Length > longest.Length ? next : longest,

fruit => fruit.ToUpper());

Console.WriteLine(longestFruit); // 输出 "BANANA"

注意事项

  • 性能 :对于大数据集,使用 Aggregate 方法可能会影响性能。

  • 空值检查:在实际使用中,应添加空值检查以避免异常。

通过这些示例,可以看出 Aggregate 方法在处理复杂聚合操作时非常有用。

相关推荐
foundbug9992 小时前
C#实现的自动升级系统
服务器·网络·c#
小鸡吃米…2 小时前
Python - 构造函数
开发语言·python
moonquakeTT2 小时前
C++:智能指针
开发语言·c++
hoiii1872 小时前
基于MATLAB实现无监督数据建模
开发语言·matlab
码界奇点2 小时前
基于Go语言的AI接口管理与分发系统设计与实现
开发语言·人工智能·ai·golang·毕业设计·go语言·源代码管理
bybitq2 小时前
深入浅出 Go 流程控制:从循环到延迟执行
开发语言·后端·golang
Autumn72992 小时前
【python】 日志打印、垃圾回收
开发语言·python
Lvan的前端笔记3 小时前
python:列表推导式(List Comprehension)
开发语言·python·list
李小先3 小时前
supersonic——PARSING阶段
开发语言·python