Dot-Net

Linq 將復雜類型聚合成一個字元串

  • October 2, 2009

我已經看到 .net Aggregate 函式的簡單範例是這樣工作的:

string[] words = { "one", "two", "three" };
var res = words.Aggregate((current, next) => current + ", " + next);
Console.WriteLine(res);

如果您希望聚合更複雜的類型,如何使用“聚合”函式?例如:一個具有 2 個屬性的類,例如 ‘key’ 和 ‘value’,並且您想要這樣的輸出:

"MyAge: 33, MyHeight: 1.75, MyWeight:90"

你有兩個選擇:

  1. 投影到 astring然後聚合:
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);

這樣做的好處是使用第一個string元素作為種子(沒有前置“,”),但會為程序中創建的字元串消耗更多記憶體。 2. 使用接受種子的聚合重載,可能是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);

第二個委託將我們StringBuilder轉換為string,使用條件來修剪開始的“,”。

引用自:https://stackoverflow.com/questions/1507501