Using Enumerable.Aggregate in System.Collection.Generic.Dictionary

Let's say that I have a common data dictionary like this (hopefully the notation will be clear here):

{"param1" => "value1", "param2" => "value2", "param3" => "value3"}

I'm trying to use the Enumerable.Aggregate function to dump every entry in the dictionary and output something like this:

"/ param1 = value1; / param2 = value2; / param3 = value3"

If I put together a list, it would be easy. With the help of a dictionary, I get key / value pairs.

+2


source to share


3 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));

      

+8


source


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);

      

+1


source


I think you are looking for something like this:

var str = dic.Aggregate("", (acc, item) => {
    if (acc != "")
        acc += "; ";

    acc += "/" + item.Key + "=" + item.Value;

    return acc;
});

      

0


source







All Articles