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

相关推荐
青岑CTF1 小时前
攻防世界-Ics-05-胎教版wp
开发语言·安全·web安全·网络安全·php
Li emily1 小时前
如何通过外汇API平台快速实现实时数据接入?
开发语言·python·api·fastapi·美股
码云数智-园园1 小时前
使用 C# 将 PowerPoint 演示文稿高效转换为 PDF 格式
c#
APIshop2 小时前
Java 实战:调用 item_search_tmall 按关键词搜索天猫商品
java·开发语言·数据库
血小板要健康2 小时前
Java基础常见面试题复习合集1
java·开发语言·经验分享·笔记·面试·学习方法
淼淼7632 小时前
安装jdk1.8
java·开发语言
PfCoder2 小时前
WinForm真入门(23)---PictureBox 控件详细用法
开发语言·windows·c#·winform
Legendary_0082 小时前
Type-C 一拖二快充线:突破单口限制的技术逻辑
c语言·开发语言
过期动态2 小时前
Java开发中的@EnableWebMvc注解和WebMvcConfigurer接口
java·开发语言·spring boot·spring·tomcat·maven·idea
csbysj20203 小时前
Web 标准
开发语言