使用LINQ查询中的ToDictionary()允许重复的键

3

我需要从字典中获取键/值对。但我不希望它允许重复的键。

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

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


1
https://dev59.com/lHVC5IYBdhLWcg3w7Vtq - Oleks
1
也许他是在测试 Stackoverflow 字典是否允许重复的键?:-P - Steven Ryssaert
@Alex ToLookup 对我的情况没有帮助。我需要 Key/Value 访问以供以后使用... - msfanboy
1
你如何期望处理具有重复键的键值查找?要么它不会起作用,要么你需要先按键值分组。 - Massif
@msfanboy:你可以通过使用索引器按键访问值;例如 dictionary[key],这将获取一个类型为 IEnumerable<string> 的对象,其中包含您的值。 - Oleks
显示剩余2条评论
1个回答

7
使用 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}}),则可以获取类型为IEnumerable<KeyValuePair<string, string>>的结果:

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循环,并且无法访问Value。我只能找到Keys属性。 - msfanboy
1
@msfanboy:Dictionary 将键映射到值,而 Lookup 则将键映射到一个或多个值。Dictionary 不允许多个值具有相同的键,而 Lookup 允许。您希望返回什么样的结构? - Oleks
非常好的解决方案,Alex!这正是我所想的。我尝试了List<KeyValuePair<string,string>>但我错过了你的Select :) - msfanboy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接