假设我有generic dictionary这样的数据(我希望这里的符号很清楚):
{ “param1”=> “VALUE1” “param2”=> “值2”, “param3”=> “值3” }
我正在尝试使用Enumerable.Aggregate函数折叠字典中的每个条目并输出如下内容:
“/ param1 = value1; / param2 = value2; / param3 = value3”
如果我正在汇总列表,这很容易。随着字典,我被键/值对绊倒了。
答案 0 :(得分:8)
您不需要Aggregate
:
String.Join("; ",
dic.Select(x => String.Format("/{0}={1}", x.Key, x.Value)).ToArray())
如果你真的想使用它:
dic.Aggregate("", (acc, item) => (acc == "" ? "" : acc + "; ")
+ String.Format("/{0}={1}", item.Key, item.Value))
或者:
dic.Aggregate("",
(acc, item) => String.Format("{0}; /{1}={2}", acc, item.Key, item.Value),
result => result == "" ? "" : result.Substring(2));
答案 1 :(得分:1)
我认为这符合您的需求:
var dictionary = new Dictionary<string, string> {{"a", "alpha"}, {"b", "bravo"}, {"c", "charlie"}};
var actual = dictionary.Aggregate("", (s, kv) => string.Format("{0}/{1}={2}; ", s, kv.Key, kv.Value));
Assert.AreEqual("/a=alpha; /b=bravo; /c=charlie; ", actual);
答案 2 :(得分:0)
我认为你要找的是这样的:
var str = dic.Aggregate("", (acc, item) => {
if (acc != "")
acc += "; ";
acc += "/" + item.Key + "=" + item.Value;
return acc;
});