Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a LINQ query into a Dictionary<string, string[]>

I've got a query that returns something of the following format:

{ "tesla", "model s" }
{ "tesla", "roadster" }
{ "honda", "civic" }
{ "honda", "accord" }

and I'd like to convert that to a dictionary of <string, string[]> like so:

{ "tesla" : ["model s", "roadster"],  "honda" : ["civic", "accord"] }

I've tried with this:

var result = query.Select(q => new { q.Manufacturer, q.Car}).Distinct().ToDictionary(q => q.Manufacturer.ToString(), q => q.Car.ToArray()); 

but so far I am not having any luck. I think what this is doing is actually trying to add individual items like "tesla" : ["model s"] and "tesla" : ["roadster"] and that's why it's failing ... any easy way to accomplish what I am trying to do in LINQ?

like image 714
Brian D Avatar asked Jul 03 '13 18:07

Brian D


2 Answers

You would need to group each item by the key first, then construct the dictionary:

result = query.Select(q => new { q.Manufacturer, q.Car}).Distinct()
              .GroupBy(q => q.Manufacturer)
              .ToDictionary(g => g.Key, 
                            g => g.Select(q => q.Car).ToArray());

Of course, an ILookup<string, string> much easier:

result = query.Select(q => new { q.Manufacturer, q.Car }).Distinct()
              .ToLookup(q => q.Manufacturer, q => q.Car);
like image 119
p.s.w.g Avatar answered Sep 25 '22 20:09

p.s.w.g


You're looking for ToLookup if you would like the results to be grouped into a dictionary-like object:

var result = query.Select(q => new { q.Manufacturer, q.Car})
                  .Distinct()
                  .ToLookup(q => q.Manufacturer.ToString(), q => q.Car);

Otherwise you will have to group the results first:

var result = query.Select(q => new { q.Manufacturer, q.Car })
                  .Distinct()
                  .GroupBy(q => q.Manufacturer)
                  .ToDictionary(gg => gg.Key,
                                gg => gg.Select(q => q.Car).ToArray());
like image 35
user7116 Avatar answered Sep 24 '22 20:09

user7116