Mys*_*ter 27 .net linq asp.net string-concatenation
我已经看到了.net Aggregate函数的简单示例:
string[] words = { "one", "two", "three" };
var res = words.Aggregate((current, next) => current + ", " + next);
Console.WriteLine(res);
Run Code Online (Sandbox Code Playgroud)
如果您希望聚合更复杂的类型,如何使用'Aggregate'函数?例如:一个具有2个属性的类,例如'key'和'value',你想要输出如下:
"MyAge: 33, MyHeight: 1.75, MyWeight:90"
Run Code Online (Sandbox Code Playgroud)
dah*_*byk 48
您有两种选择:
项目到a string然后汇总:
var values = new[] {
new { Key = "MyAge", Value = 33.0 },
new { Key = "MyHeight", Value = 1.75 },
new { Key = "MyWeight", Value = 90.0 }
};
var res1 = values.Select(x => string.Format("{0}:{1}", x.Key, x.Value))
.Aggregate((current, next) => current + ", " + next);
Console.WriteLine(res1);
Run Code Online (Sandbox Code Playgroud)
这样做的好处是可以使用第一个string元素作为种子(没有前置","),但会为进程中创建的字符串消耗更多内存.
使用接受种子的聚合重载,可能是StringBuilder:
var res2 = values.Aggregate(new StringBuilder(),
(current, next) => current.AppendFormat(", {0}:{1}", next.Key, next.Value),
sb => sb.Length > 2 ? sb.Remove(0, 2).ToString() : "");
Console.WriteLine(res2);
Run Code Online (Sandbox Code Playgroud)
第二个代表将我们StringBuilder转换为string,使用条件来修剪起始",".
Aggregate 有 3 个重载,因此您可以使用具有不同类型的重载来累积您正在枚举的项目。
您需要传入一个种子值(您的自定义类),以及一种将种子与一个值合并的方法。例子:
MyObj[] vals = new [] { new MyObj(1,100), new MyObj(2,200), ... };
MySum result = vals.Aggregate<MyObj, MySum>(new MySum(),
(sum, val) =>
{
sum.Sum1 += val.V1;
sum.Sum2 += val.V2;
return sum;
}
Run Code Online (Sandbox Code Playgroud)