允许来自LINQ查询的ToDictionary()重复键

msf*_*boy 3 .net c# linq dictionary duplicates

我需要字典中的Key/Value内容.我不需要的是它不允许重复的密钥.

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);
Run Code Online (Sandbox Code Playgroud)

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

Ale*_*lex 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);
Run Code Online (Sandbox Code Playgroud)

编辑:如果你希望得到一个"普通"的结果集(例如{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
        )
    );
Run Code Online (Sandbox Code Playgroud)