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

其他键: 其他值

相关推荐
阿昭L12 分钟前
Windows SEH机制(二)
windows
Eiceblue20 分钟前
通过 C# 解析 HTML:文本提取 + 结构化数据获取
c#·html·.net·visual studio
存在即合理L27 分钟前
Windows中安装Anaconda后如何在powershell使用conda activate命令
windows·conda
l1t40 分钟前
在Windows的WSL中试用GizmoSQL UI连接GizmoSQL数据库服务器
数据库·windows·ui
SunnyDays10111 小时前
使用 C# 将 Excel XLSX 或 XLS 转换为 HTML:完整指南
c#·excel转html·xlsx转html·xls转html
时光追逐者1 小时前
一款基于 .NET Avalonia 开源免费、快速、跨平台的图片查看器
c#·.net·图片查看器
熊猫钓鱼>_>1 小时前
【开源鸿蒙跨平台开发先锋训练营】Day 8:鸿蒙 Next + React Native 实战:打造丝滑的四Tab底部导航体验
react native·开源·list·tab·harmonyos·鸿蒙·next
sg_knight1 小时前
Claude Code 安装指南(Windows / macOS)
windows·macos·llm·ai编程·claude·code·claude-code
Digitally1 小时前
如何在Windows系统中录制屏幕音频
windows·电脑
suxuyu011 小时前
ubuntu通过windows主机访问网络
网络·windows·ubuntu