c# List<T>.Aggregate
List<T>.Aggregate
方法的定义:
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 是集合中的元素,即字典中的键值对。
示例
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
其他键: 其他值