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

相关推荐
南境十里·墨染春水10 分钟前
C++笔记 STL——set
开发语言·c++·笔记
L16247611 分钟前
Win11 共享→Windows Server 访问故障总结(极简可复用)
开发语言·windows·php
.柒宇.1 小时前
FastAPI 基础指南:从入门到实战
开发语言·python·fastapi
xyq20241 小时前
Go 错误处理
开发语言
JAVA面经实录9171 小时前
企业级java+LangChain4j-RAG系统 限流熔断降级
java·开发语言·分布式·langchain
Slow菜鸟1 小时前
Codex CLI 教程(五)| AI 驱动项目从零到一:面向 Java 全栈工程师打造个人 ECC(V2版)
java·开发语言·人工智能
lsx2024061 小时前
Julia 基本运算符
开发语言
2501_921649492 小时前
企业定制金融数据 API:从架构设计到 Python 接入实战
大数据·开发语言·python·websocket·金融·量化
直奔標竿2 小时前
SpringAI + RAG + MCP + Agent 零基础全栈实战(完结篇)| 27课完整汇总,Java开发者AI转型必看
java·开发语言·人工智能·spring boot·后端·spring
reasonsummer2 小时前
【教学类-160-13】20260422 AI视频培训-练习013“豆包AI视频《师幼互动》+豆包图片风格:CG动画”
开发语言·python