Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using Enumerable.Aggregate on System.Collection.Generic.Dictionary

Tags:

c#

linq

generics

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.

like image 673
brad Avatar asked Mar 13 '26 04:03

brad


2 Answers

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));
like image 154
mmx Avatar answered Mar 15 '26 19:03

mmx


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);
like image 39
neontapir Avatar answered Mar 15 '26 19:03

neontapir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!