5

我有一个返回以下格式的查询:

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

我想把它转换成这样的字典<string, string[]>

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

我试过这个:

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

但到目前为止,我没有任何运气。我认为这实际上是在尝试添加单个项目,例如"tesla" : ["model s"]"tesla" : ["roadster"]这就是它失败的原因......有什么简单的方法可以完成我在 LINQ 中尝试做的事情吗?

4

4 回答 4

3

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);
于 2013-07-03T18:44:46.233 回答
3

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());
于 2013-07-03T18:45:49.543 回答
1

你要的是GroupBy(),其次ToDictionary()

例子:

var result = query.GroupBy(q => q.Manufacturer).ToDictionary(q => q.Key, q => q.Value.ToArray());

什么GroupBy()是将具有相同匹配键选择器的所有元素分组。因此,当您告诉它时GroupBy(q => q.Manufacturer),具有相同制造商的所有元素将组合在一起IEnumerable<T>

于 2013-07-03T18:43:49.170 回答
0

使用ToLookup

var table = pairs.ToLookup(kvp => kvp.Key, kvp => kvp.Value);

foreach(var i in table["tesla"])
   Console.WriteLine(i);
于 2013-07-03T18:44:10.270 回答