0

当我运行此代码时:

List<string> list = new List<string>();
list.Add("a");
list.Add("b");
list.Add("c");
list.Add("d");

string s = list.Aggregate((total, item) => total += item + ",");

我希望 s 是:

a,b,c,d,

但相反,s 是:

ab,c,d,

谁能告诉我为什么它不在第一个和第二个索引之间附加逗号?

谢谢

4

3 回答 3

3

你会发现这行得通

string s = list.Aggregate(string.Empty, (total, item) => total += item + ",");

如果您对此进行测试,您会看到原因:

var total = "a";
var item = "b";
var s = total += item + ",";

这导致“ab”,

对 total 使用初始的空种子值((string)null 或 string.Empty)将为您提供预期的结果。

于 2012-05-29T20:22:36.003 回答
2

聚合的以下重载将起作用:

string s = list.Aggregate<string, string>(null, (total, item) => total + item + ",");

基本上,您使用的版本将“a”作为total初始条件的值,然后使用提供的 lambda 附加其余部分。我的版本从总计开始null,然后附加每个项目。

于 2012-05-29T20:23:24.880 回答
1

尝试和工作

string s = list.Aggregate((total, item) => total += "," + item); 

问题是:运行时第一次调用 Aggregate Func 时total是“a”,item 是“b”。实际上,此扩展旨在执行计算而不是连接字符串。

但是请注意,结果字符串是 a,b,c,d (没有结尾逗号)我不知道这是否更可取(取决于您对结果字符串的使用)

于 2012-05-29T20:24:08.263 回答