PositiveGuy
PositiveGuy

Reputation: 47763

Group Dictionary by Key

var invalidPageNumberAndSize = new Dictionary<string, string>
{
    {"0","0"},
    {"0", ""},
    {"", "0"},
    {"abc", ""},
    {"", "abc"},
    {"abc", "abc"},
};

this will error if I try to loopit because I have 2 of the same key for each of these (I have 2 "0", and so on) so it'll throw a dup key error in my loop.

How can I make this work?

Upvotes: 0

Views: 72

Answers (2)

CharlesNRice
CharlesNRice

Reputation: 3259

You could look at Lookup. It's going to act kind of like the dictionary but it's immutable and will group the data. You would use Contains instead of contains key and you don't get the nice initializer syntax.

var invalidPageNumberAndSizeData = new[] {
        new { key = "0", value = "0"},
        new { key = "0",  value = ""},
        new { key = "",  value = "0"},
        new { key = "abc",  value = ""},
        new { key = "",  value = "abc"},
        new { key = "abc",  value = "abc"}
    };


var invalidPageNumberAndSize = invalidPageNumberAndSizeData.ToLookup(c => c.key, c => c.value);
var isAbc = invalidPageNumberAndSize.Contains("abc");
var abcData = invalidPageNumberAndSize["abc"];

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564641

You can't use a dictionary if you need to have multiple, duplicate keys.

One option is that you can have a Dictionary<string,List<string>> or similar (where each key can have multiple values. This is a bit more work to populate, but supports this type of scenario. Another option would be to use a Lookup.

That being said, given your variable names, I'd rethink what you're trying to do. Storing a "size" and a "page number" as strings seems inappropriate.

Upvotes: 2

Related Questions