Allow duplicate keys with ToDictionary() from LINQ query
I need the Key/Value stuff from a Dictionary. What I do not need is that it does not allow duplicate Keys.
Regex template = new Regex(@"\{(?<key>.+?)\}(?<value>[^{}]*)");
IDictionary<string, string> dictionary = template.Matches(MyString)
                                             .Cast&l开发者_StackOverflow中文版t;Match>()
                                             .ToDictionary(x => x.Groups["key"].Value, x => x.Groups["value"].Value);
How can I return the Dictionary allowing duplicate keys?
Use the Lookup class:
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);
EDIT: If you expect to get a "plain" resultset (e.g. {key1, value1}, {key1, value2}, {key2, value2} instead of {key1, {value1, value2} }, {key2, {value2} }) you could get the result of type 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
        )
    );
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论