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 方法在处理复杂聚合操作时非常有用。

相关推荐
持敬chijing12 分钟前
PHP开发-环境搭建-安装phpstudy-vscode工具
开发语言·vscode·php
charlie11451419143 分钟前
Cinux · 第一次跳进 Ring 3:用户态与特权隔离
开发语言·c++·操作系统·开源项目
躺不平的理查德1 小时前
Windows C++ 第三方库使用流程备忘录--OpenCV
开发语言·c++
菜冻鱼1 小时前
Python-sklearn-评估指标
开发语言·人工智能·python·机器学习·numpy·pandas·sklearn
你挚爱的强哥1 小时前
【exportExcel】单纯靠js不用任何其他第三方插件导出xls格式文件
开发语言·javascript·ecmascript
Hello_Damon_Nikola2 小时前
AC7911从入门到精通
开发语言·嵌入式硬件·物联网·php
worxfr2 小时前
Go 并发控制:从 Channel 方向约束到实战模式
开发语言·后端·golang
带鱼吃猫2 小时前
预处理器:宏、运算符与条件编译
c语言·开发语言
小小龙学IT2 小时前
C++ std::vector 底层实现深度解析:内存布局、扩容策略、移动语义与迭代器失效
开发语言·c++·算法
码匠许师傅3 小时前
【C++ 面试真题】聊聊 volatile 和 mutable
开发语言·c++·面试