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

其他键: 其他值

相关推荐
未知违规用户36 分钟前
大模型项目:RAG项目实战与FlagEmbedding模型
人工智能·windows·python·深度学习
名字还没想好☜11 小时前
Python itertools 实战:用 groupby、chain、islice 优雅处理大数据流
linux·windows·python·迭代器·itertools
code bean12 小时前
【C#】 `Channel<T>` 深度解析:生产者-消费者模式的现代解法
数据结构·c#
ziguo112213 小时前
深入浅出 C/C++ 数据类型:从入门到踩坑
linux·c语言·c++·windows·visual studio
阿扬ABCD15 小时前
ipmitool的Windows版本编译
windows·驱动开发
吴可可12316 小时前
C# CAD二次开发:合并首尾重合多段线
c#
EIP低代码平台17 小时前
EIP低代码平台 - 应用管理 - 表单设计
低代码·c#·权限·工作流·netcore
czhc114007566317 小时前
726:zoffset
c#
王维同学17 小时前
Credential Provider、Filter 与 PLAP 的 CLSID 枚举
c++·windows·安全·注册表
寒水馨19 小时前
Windows下载、安装 Codex CLI(附安装包codex-x86_64-pc-windows-msvc.exe)
windows·rust·codex·终端工具·自动化编程·codex cli·ai编码代理