c# List<T>.Aggregate

List<T>.Aggregate 方法的定义:

csharp 复制代码
public TAccumulate Aggregate<TAccumulate>(TAccumulate seed, Func<TAccumulate, T, TAccumulate> func)

参数解析如下:

TAccumulate seed:初始累积值,也是累积的起始值(默认值)。
Func<TAccumulate, T, TAccumulate> func:累积计算的逻辑函数,接受两个参数,第一个参数是当前的累积值,第二个参数是集合中的元素,返回一个新的累积值。

seed:初始累积值是一个空的 List<Dictionary<string, string>>,通过创建实例 new List<Dictionary<string, string>>() 进行初始化。

func:逻辑函数是一个匿名函数,由 (groups, kvp) => { ... } 定义。其中,groups 是当前的累积值,对应空列表 List<Dictionary<string, string>>,而 kvp 是集合中的元素,即字典中的键值对。

示例

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        Dictionary<string, string> dic = new Dictionary<string, string>
        {
            { "Pn1#", "Value1" },
            { "Pn2##", "Value2" },
            { "Pn3###", "Value3" },
            { "其他键", "其他值" }
        };

        List<Dictionary<string, string>> result = dic.Aggregate(
            new List<Dictionary<string, string>>(), // 初始累积值
            (groups, kvp) => // 累积计算的逻辑函数
            {
                var key = kvp.Key.Replace("#", "");
                if (key.StartsWith("Pn"))
                {
                    groups.Add(new Dictionary<string, string>
                    {
                        { key, kvp.Value }
                    });
                }
                else if (groups.Count > 0)
                {
                    var lastGroup = groups.Last();
                    lastGroup[key] = kvp.Value;
                }
                return groups;
            }
        );

        // 输出结果
        foreach (var group in result)
        {
            foreach (var kvp in group)
            {
                Console.WriteLine($"{kvp.Key}: {kvp.Value}");
            }
        }
    }
}

Pn1: Value1

Pn2: Value2

Pn3: Value3

其他键: 其他值

相关推荐
视觉人机器视觉1 小时前
机器视觉中的3D高反光工件检测
人工智能·3d·c#·视觉检测
CodeCraft Studio1 小时前
文档处理控件TX Text Control系列教程:使用 .NET C# 从 PDF 文档中提取基于模板的文本
pdf·c#·.net
一念春风1 小时前
C# 背景 透明 抗锯齿 (效果完美)
开发语言·c#
Igallta_8136221 小时前
【小游戏】C++控制台版本俄罗斯轮盘赌
c语言·开发语言·c++·windows·游戏·游戏程序
且听风吟ayan2 小时前
leetcode day19 844+977
leetcode·c#
C137的本贾尼2 小时前
解决 LeetCode 串联所有单词的子串问题
算法·leetcode·c#
wave_sky3 小时前
Visual Studio中打开多个项目
ide·windows·visual studio
donglxd4 小时前
防御黑客系列-第一集-电脑登录记录提示和登录远程推送
windows·网络安全·电脑·系统安全
CoderIsArt4 小时前
C# 中的一个特性(Attribute)[ThreadStatic]
c#
心疼你的一切5 小时前
C# 中关于补位的写法 PadLeft,PadRight 函数
开发语言·unity·c#·游戏引擎·csdn·心疼你的一切