visc
visc

Reputation: 4959

Creating dictionaries with pre-defined keys C#

I'm looking for a way to define a dictionary for reuse. ie. I can create the dictionary object without having to populate it with the values I want.

Here is what I have currently (note code not tested, just example)

public Dictionary<string, string> NewEntryDictionary()
{
    Dictionary<string, string> dic = new Dictionary<string, string>();

    // populate key value pair
    foreach(string name in Enum.GetNames(typeof(Suits))
    {
        dic.Add(name, "");
    }

    return dic;
}

The end result should be a new dictionary object with a predefined set of keys. But I want to avoid doing it this way.

Upvotes: 3

Views: 1513

Answers (2)

Ole Albers
Ole Albers

Reputation: 9315

If you do ONLY want to save values according to your enum, use Dictionary<Suits,String> instead of Dictionary<String,String>

Everything else, Jon already said. Use LinQ for a bit more "fancy" look. But that does not do better performance

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1504122

It's not really clear whether you're concerned about the amount of code you've written, or the efficiency of it. From an efficiency perspective, it's fine - it's O(N), but that's hard to avoid if you're populating a dictionary with N entries.

You can definitely make the source code shorter though, using LINQ:

public Dictionary<string, string> NewEntryDictionary()
{
    return Enum.GetNames(typeof(Suits)).ToDictionary(name => name, name => "");
}

That won't be any more efficient, of course... it's just shorter code.

Upvotes: 5

Related Questions