将LINQ查询转换为字典<;字符串,字符串[]>;
本文关键字:字符串 gt LINQ 查询 字典 lt 转换 | 更新日期: 2023-09-27 18:20:50
我有一个查询,它返回以下格式:
{ "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中要做的事情吗?
您需要先按关键字对每个项进行分组,然后构造字典:
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);
如果您希望将结果分组到类似字典的对象中,那么您正在寻找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());
您想要的是GroupBy()
,然后是ToDictionary()
。
示例:
var result = query.GroupBy(q => q.Manufacturer).ToDictionary(q => q.Key, q => q.Value.ToArray());
GroupBy()
所做的是对具有相同匹配密钥选择器的所有元素进行分组。因此,当您将其告知GroupBy(q => q.Manufacturer)
时,所有具有相同制造商的元素都将分组为IEnumerable<T>
。
使用ToLookup:
var table = pairs.ToLookup(kvp => kvp.Key, kvp => kvp.Value);
foreach(var i in table["tesla"])
Console.WriteLine(i);