【问题标题】:Allow duplicate keys with ToDictionary() from LINQ query允许来自 LINQ 查询的 ToDictionary() 重复键
【发布时间】:2011-07-06 14:02:11
【问题描述】:

我需要字典中的键/值内容。我不需要的是它不允许重复的密钥。

Regex template = new Regex(@"\{(?<key>.+?)\}(?<value>[^{}]*)");
IDictionary<string, string> dictionary = template.Matches(MyString)
                                             .Cast<Match>()
                                             .ToDictionary(x => x.Groups["key"].Value, x => x.Groups["value"].Value);

如何返回允许重复键的字典?

【问题讨论】:

  • 是否可以使用 List>?
  • 也许他在测试 Stackoverflow 字典是否允许重复键? :-P
  • @Alex ToLookup 对我没有帮助。我需要键/值访问以供以后使用...
  • 您希望 key -> value 查找如何处理重复的键?要么它不起作用,要么你想先按键值分组。

标签: c# .net linq dictionary duplicates


【解决方案1】:

使用Lookup 类:

Regex template = new Regex(@"\{(?<key>.+?)\}(?<value>[^{}]*)");
ILookup<string, string> dictionary = template.Matches(MyString)
    .Cast<Match>()
    .ToLookup(x => x.Groups["key"].Value, x => x.Groups["value"].Value);

编辑:如果你希望得到一个“普通”的结果集(例如{key1, value1}{key1, value2}{key2, value2} 而不是{key1, {value1, value2} }, {key2, {value2} }),你可以获得@987654322 类型的结果@:

Regex template = new Regex(@"\{(?<key>.+?)\}(?<value>[^{}]*)");
ILookup<string, string> dictionary = template.Matches(MyString)
    .Cast<Match>()
    .Select(x =>
        new KeyValuePair<string, string>(
            x.Groups["key"].Value,
            x.Groups["value"].Value
        )
    );

【讨论】:

  • 是的,我当然可以这样做,但是我必须使用 for 循环并且我无法访问该值。我只能找到 Keys 属性?
  • @msfanboy:当Lookup 将键映射到一个或多个值时,Dictionary 将键映射到值。 Dictionary 不允许多个值具有相同的键,而 Lookup 允许。您希望返回什么样的结构?
  • 非常好的解决方案,亚历克斯!正是我的意思。我试过 List> 但我错过了你的 Select :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-07
  • 2019-02-18
  • 1970-01-01
  • 2018-08-31
  • 1970-01-01
  • 2021-09-27
相关资源
最近更新 更多