我有一个返回以下格式的查询:
{ "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 :(得分:3)
您需要先按键对每个项目进行分组,然后构建字典:
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);
答案 1 :(得分:3)
如果您希望将结果分组到类似字典的对象中,那么您正在寻找ToLookup
:
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());
答案 2 :(得分: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>
。
答案 3 :(得分:0)
使用ToLookup:
var table = pairs.ToLookup(kvp => kvp.Key, kvp => kvp.Value);
foreach(var i in table["tesla"])
Console.WriteLine(i);