gpt4 book ai didi

c# - 添加到 C# 字典 : cannot convert from 'string' to 'System.Collections.Specialized.NameValueCollection'

转载 作者:太空狗 更新时间:2023-10-29 20:07:00 24 4
gpt4 key购买 nike

我有一个数据源,其中包含 3 个不同的值,如下所示,

List<Configuration> lst = new List<Configuration>
{
new Configuration{Name="A", Config="X", Value="1"},
new Configuration{Name="A", Config="X", Value="2"},
new Configuration{Name="B", Config="Y", Value="2"}
};

public class Configuration
{
public string Name { get; set; }
public string Config { get; set; }
public string Value { get; set; }
}

在这里,我想遍历整个源,并希望将“Name”值保留为 KEY,将“Config”和“Value”保留到“NameValueCollection”中。

为此,我使用如下字典,

var config = new Dictionary<string, NameValueCollection>();

但是在添加到这本词典时我遇到了 2 个问题,

foreach(var c in lst)
{
config.Add(c.Name, new NameValueCollection { c.Config, c.Value });
}
  1. 重复键 (Name="A")
  2. 这一行出错,new NameValueCollection { c.Config, c.Value });

注意 - 我想要 X 的 1 和 2(在重复键的情况下)

有没有更好的C#集合或者如何解决上面的错误。

谢谢!

最佳答案

您可以使用 lookups 的字典(它表示一个集合,其中键映射到多个值):

var config = lst.GroupBy(cfg => cfg.Name)
.ToDictionary(g => g.Key,
g => g.ToLookup(cfg => cfg.Config, cfg => cfg.Value));

配置类型将是

Dictionary<string, ILookup<string, string>>

访问值:

config["A"]["X"] // gives you IEnumerable<string> with values ["1","2"]

关于c# - 添加到 C# 字典 : cannot convert from 'string' to 'System.Collections.Specialized.NameValueCollection' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43629002/

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