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

其他键: 其他值

相关推荐
hqwest39 分钟前
C#WPF实战出真汁08--【消费开单】--餐桌面板展示
c#·wpf·ui设计·wpf界面设计
orangapple43 分钟前
WPF 打印报告图片大小的自适应(含完整示例与详解)
c#·wpf
七仔的博客1 小时前
【摸鱼办公神器】七仔的桌面工具超进化 -> 灵卡面板 v1.1.9
windows·神器·摸鱼
码农阿豪2 小时前
Windows从零到一安装KingbaseES数据库及使用ksql工具连接全指南
数据库·windows
CC__xy10 小时前
demo 通讯录 + 城市选择器 (字母索引左右联动 ListItemGroup+AlphabetIndexer)笔记
windows
★YUI★16 小时前
学习游戏制作记录(玩家掉落系统,删除物品功能和独特物品)8.17
java·学习·游戏·unity·c#
谷宇.16 小时前
【Unity3D实例-功能-拔枪】角色拔枪(二)分割上身和下身
游戏·unity·c#·游戏程序·unity3d·游戏开发·游戏编程
LZQqqqqo17 小时前
C# 中 ArrayList动态数组、List<T>列表与 Dictionary<T Key, T Value>字典的深度对比
windows·c#·list
季春二九17 小时前
Windows 11 首次开机引导(OOBE 阶段)跳过登录微软账户,创建本地账户
windows·microsoft
芥子沫18 小时前
Jenkins常见问题及解决方法
windows·https·jenkins