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

相关推荐
AI人工智能+电脑小能手1 分钟前
【大白话说Java面试题 第106题】【并发篇】第6题:synchronized 锁的锁对象可以是什么?
java·开发语言·面试
质造者1 分钟前
Python 本地 RAG 实战 | Ollama+ChromaDB 实现 PDF 离线智能问答
开发语言·python·pdf·大模型·rag
slandarer8 分钟前
MATLAB | 韦恩图的高阶版: UpSet图 更新升级啦!
开发语言·matlab
Leweslyh9 分钟前
3GPP TS 28.312 意图驱动管理服务 — 极详细通俗解读
开发语言·php
swordbob21 分钟前
Spring事务失效的场景
java·开发语言·spring
catchadmin35 分钟前
PHP 在领域驱动(DDD)设计中的核心实践
开发语言·php
FuckPatience43 分钟前
C# 链表元素的引用地址分析
链表·c#
SilentSamsara1 小时前
MLflow 实验追踪与模型注册:从实验到生产的可复现工作流
开发语言·人工智能·pytorch·python·青少年编程
dongf20191 小时前
R语言朴素贝叶斯算法---iris数据集
开发语言·算法·数据分析·r语言
下班走回家1 小时前
RAG 技术的进化:从朴素检索到 Agentic RAG
开发语言·人工智能·python