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?
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:
By the way you can use following code to build required string:
String.Join(", ", dic.Select(kvp => kvp.Key + " = " + kvp.Value));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With