3

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<Match>()
                                             .ToDictionary(x => x.Groups["key"].Value, x => x.Groups["value"].Value);

How can I return the Dictionary allowing duplicate keys?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
msfanboy
  • 5,273
  • 13
  • 69
  • 120

1 Answers1

7

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
        )
    );
Oleks
  • 31,955
  • 11
  • 77
  • 132
  • yes of course I can do this, but then I have to use the for-loop AND I can not access the Value. I can only find the Keys property ? – msfanboy Mar 01 '11 at 15:22
  • 1
    @msfanboy: the `Dictionary` maps key to value when `Lookup` maps key to one or more values. the `Dictionary` doesn't allow several values to have the same key when `Lookup` does. What kind of structure do you expect to return? – Oleks Mar 01 '11 at 15:27
  • very good solution Alex! Exactly what I meant. I tried List> but I missed your Select :) – msfanboy Mar 02 '11 at 08:45