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

其他键: 其他值

相关推荐
UNbuff_03 小时前
Windows netstat 命令使用说明
windows
您的通讯录好友3 小时前
conda环境导出
linux·windows·conda
上位机付工5 小时前
C#与倍福TwinCAT3进行ADS通信
开发语言·c#
土了个豆子的6 小时前
02.继承MonoBehaviour的单例模式基类
开发语言·visualstudio·单例模式·c#·里氏替换原则
疯狂的维修6 小时前
c#中public类比博图
c#·自动化
子兮曰7 小时前
🔥C盘告急!WSL磁盘暴增?三招秒清20GB+空间
前端·windows·docker
学历真的很重要9 小时前
Claude Code Windows 原生版安装指南
人工智能·windows·后端·语言模型·面试·go
李游Leo9 小时前
LaTeX TeX Live 安装与 CTAN 国内镜像配置(Windows / macOS / Linux 全流程)
linux·windows·macos
土了个豆子的9 小时前
03.缓存池
开发语言·前端·缓存·visualstudio·c#
Jayin_chan10 小时前
windows下安装claude code+国产大模型glm4.5接入(无需科学上网)
windows·claude code·glm4.5