转换LINQ查询到词典<字符串,字符串[]>

问题描述:

我已经得到了返回以下格式的一些查询:转换LINQ查询到词典<字符串,字符串[]>

{ "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中要做的事情?

+0

可能的复制http://*.com/questions/7325278的/组按在-LINQ? – feralin

您将需要组通过密钥每个项目,然后再构建词典:

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

当然,一个ILookup<string, string>容易得多:

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

“当然”...(哈哈?) – sehe

+0

优秀。谢谢。这正是我需要的。 –

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

实施例:

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

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

+0

你能详细说一下吗? –

使用ToLookup

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

foreach(var i in table["tesla"]) 
    Console.WriteLine(i); 

您正在寻找ToLookup如果您愿意IKE结果被分为一类字典对象:

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

否则,你将不得不组结果第一:

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