Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Aggregate method of Dictionary<> in C#?

I'm a beginner in C#. I have a dictionary like this :

{
  {"tom", "student"},
  {"rob", "teacher"},
  {"david", "lawyer"}
}

I want to form this line :

tom = student, rob = teacher, david = lawyer

I want to use Aggregate extension method of dictionary<> but when i do it like this :

Console.WriteLine(dic.Aggregate((a,b) => (a.Key + " = " + a.Value + ", " + b.Key + " = " + b.Value)));

I get this error :

Cannot convert lambda expression to delegate type.

So it seems that i'm doing it wrong. So can anybody tell me how to use this method?

like image 712
Rafael Adel Avatar asked Dec 25 '12 19:12

Rafael Adel


1 Answers

Aggregate is not a method from Dictionary, it's an extension method for IEnumerable<T>. If you want to build aggregated string:

dic.Aggregate(new StringBuilder(),
              (sb, kvp) => sb.AppendFormat("{0}{1} = {2}", 
                           sb.Length > 0 ? ", " : "", kvp.Key, kvp.Value),
              sb => sb.ToString());

Explanation:

  • First parameter is accumulator, which will accumulate result
  • Second parameter is a function, which will be invoked on each dictionary element. This function appends data to accumulator.
  • Last parameter builds result string from accumulator

By the way you can use following code to build required string:

String.Join(", ", dic.Select(kvp => kvp.Key + " = " + kvp.Value));          
like image 88
Sergey Berezovskiy Avatar answered Sep 30 '22 12:09

Sergey Berezovskiy