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?

7
  • Is it possible to use List<KeyValuePair<string, string>>? Commented Mar 1, 2011 at 15:01
  • 1
    stackoverflow.com/questions/146204/… Commented Mar 1, 2011 at 15:02
  • 1
    Maybe he was testing if the Stackoverflow Dictionary allowed duplicate keys? :-P Commented Mar 1, 2011 at 15:03
  • @Alex ToLookup does not help in my case. I need the Key/Value access for later usage... Commented Mar 1, 2011 at 15:06
  • 1
    how do you expect the key -> value lookup to work with duplicate keys? Either it's not going to work, or you want to group by the key value first. Commented Mar 1, 2011 at 15:13

1 Answer 1

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
        )
    );
Sign up to request clarification or add additional context in comments.

3 Comments

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: 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?
very good solution Alex! Exactly what I meant. I tried List<KeyValuePair<string,string>> but I missed your Select :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.