Naming convention for a C# Dictionary

How do we name a dictionary variable?

Say in my method I have Dictionary<string, List<string>> dictionary;, where the keys of the dictionary are country names and the values are lists of province/state names. How should I rename dictionary?

I know we can create a Country class for this example. But please don't mention this alternative because I'm thinking of good naming convention here.


ProvincesByCountry

I use mostly one of these:

  • CountryToStatesDictionary
  • CountryToStatesMap
  • CountryToStatesMapping

I like XtoYMap or YFromX.


ProvincesByCountry is not explicit enough, as it sounds like mapping countries to provinces one to one. When accessing ProvincesByCountry["Germany"] I'd expectedly assume one value is an object rather than a list of objects.

My personal pattern is similar:

[Plural of a noun describing the value]By[Singular of a noun describing the key]

However, if a noun describing the value is plural by its nature, then I use the postfix arrays, or lists, as in English you can't really "pluralise" a plural. I personally always stick to arrays, regardless of the actual implementation of IEnumerable or IEnumerable< T> I'm using, be that List, or Array or whatever.

In your case it turns to:

ProvinceArraysByCountry

Tells what it is with scientific precision.

I apply this rule recursively if there are dictionaries as values. The order of accessing then goes in reverse to the order of words in the name. Imagine you add planets:

ProvinceArraysByCountryByPlanet["Earth"]["Germany"][0] = "Bavaria"
ProvinceArraysByCountryByPlanet["Earth"]["Germany"][1] = "Rhineland-Palatinate"

And finally the last little stroke here. If such dictionary maps object properties and the objects themselves, then I leave out the word describing the object in the key section. Here is what I mean:

NodesByIndex[node.Index] = node; // - Do
NodesByNodeIndex[node.Index] = node; // - Don't

I use this pattern unconditionally which is good as it leaves absolutely no room for guess. Con is it generates fairly long names sometimes. But I have no idea how to have always explicit but always short names. You always have to compromise. And it's of course a matter of taste.

This pattern doesn't work (or at least you'd break your brain) when keys are also dictionaries or when you have list of dictionaries of lists of dictionaries or some other crazy exotic stuff. But I don't remember having that many levels of nesting, so I'm happy with it.