.NET Framework聚合(折叠)
示例
在每个步骤中生成一个新对象:
var elements = new[] {1,2,3,4,5}; var commaSeparatedElements = elements.Aggregate( seed: "", func: (aggregate, element) => $"{aggregate}{element},"); Console.WriteLine(commaSeparatedElements); //1,2,3,4,5,
在所有步骤中使用同一对象:
var commaSeparatedElements2 = elements.Aggregate( seed: new StringBuilder(), func: (seed, element) => seed.Append($"{element},")); Console.WriteLine(commaSeparatedElements2.ToString()); //1,2,3,4,5,
使用结果选择器:
var commaSeparatedElements3 = elements.Aggregate( seed: new StringBuilder(), func: (seed, element) => seed.Append($"{element},"), resultSelector: (seed) => seed.ToString()); Console.WriteLine(commaSeparatedElements3); //1,2,3,4,5,
如果省略种子,则第一个元素成为种子:
var seedAndElements = elements.Select(n=>n.ToString()); var commaSeparatedElements4 = seedAndElements.Aggregate( func: (aggregate, element) => $"{aggregate}{element},"); Console.WriteLine(commaSeparatedElements4); //12,3,4,5,