Creating dictionaries with predefined keys C #

I am looking for a way to define a dictionary for reuse. i.e. I can create a dictionary object without filling it with the required values.

Here is what I currently have (note code not tested, just an 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 this.

+3


source to share


2 answers


It's not entirely clear if you are worried about the amount of code written or its efficiency. In terms of efficiency, this is great - it's O (N), but it's hard to avoid if you're filling a dictionary with N elements.

You can make your code shorter using LINQ:



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

      

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

+5


source


If you want to ONLY store the values ​​according to your enum, use Dictionary<Suits,String>

insteadDictionary<String,String>



Everything else, John said. Use LinQ for a more "fancy" look. But this does not improve performance.

0


source







All Articles