Reputation: 2249
Say that i have a generic dictionary with data like this (I hope the notation is clear here):
{ "param1" => "value1", "param2" => "value2", "param3" => "value3" }
I'm trying to use the Enumerable.Aggregate function to fold over each entry in the dictionary and output something like this:
"/param1= value1; /param2=value2; /param3=value3"
If I were aggregating a list, this would be easy. With the dictionary, I'm getting tripped up by the key/value pairs.
Upvotes: 2
Views: 2151
Reputation: 422172
You don't need Aggregate
:
String.Join("; ",
dic.Select(x => String.Format("/{0}={1}", x.Key, x.Value)).ToArray())
If you really want to use it:
dic.Aggregate("", (acc, item) => (acc == "" ? "" : acc + "; ")
+ String.Format("/{0}={1}", item.Key, item.Value))
Or:
dic.Aggregate("",
(acc, item) => String.Format("{0}; /{1}={2}", acc, item.Key, item.Value),
result => result == "" ? "" : result.Substring(2));
Upvotes: 8
Reputation: 7850
I think what you are looking for is something like this:
var str = dic.Aggregate("", (acc, item) => {
if (acc != "")
acc += "; ";
acc += "/" + item.Key + "=" + item.Value;
return acc;
});
Upvotes: 0
Reputation: 4736
I believe this suits your needs:
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);
Upvotes: 1