Allow duplicate keys using ToDictionary () from LINQ query

I need Key / Value stuff from the dictionary. I do not need the fact that it does not allow duplicate keys.

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

How can I return a dictionary that allows duplicate keys?

+3
source share
1 answer

Use Search :

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 receive a "simple" set of results (eg {key1, value1}, {key1, value2}, {key2, value2}instead {key1, {value1, value2} }, {key2, {value2} }), you can get the type of results 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
        )
    );
+7
source

Source: https://habr.com/ru/post/1795520/


All Articles