gpt4 book ai didi

c# - 将 LINQ 查询转换为 Dictionary

转载 作者:太空狗 更新时间:2023-10-29 23:00:03 25 4
gpt4 key购买 nike

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

{ "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);

关于c# - 将 LINQ 查询转换为 Dictionary<string, string[]>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17455783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com