C# – Dictionaries and simple actions with them

The dictionaries in C# are quite interesting feature. For a person, coming from the VBA world ( 🙂 ), this feature is quite interesting and new. A lot has been said in the internet about dictionaries, so I will not try to say it again. With two words, dictionaries are systems of lists, with a key and a value. The key can be of any type, the value as well. You should be careful that the keys are always unique and… that is it, lets go for the example.

EnumLists

In our example, we will build a dictionary named PlayerReview, consisted of integer for a key and object from class “Footballer” for value. The object from the class “Footballer” has two properties – Age and Club. The property Club is enumerated to 4 possibilities – CSKA, Levski, Slavia and Lokomotiv. The code for the class and the enum look like this:

The interesting part starts when we fill up our dictionary:

At the first row, we initialize the Dictionary called Player Review. At the rows later, we fill it up with 5 players, giving them ID (the keys), Age (20 to 32) and Clubs (from the enum possibilities).

Once we have the Dictionary, the question is what can we do with it? With 3 foreach loops, I show how to display data for the Keys, Age and the Values, separately and united. The code looks like this:

The result at the console is the following:

EnumLists2

Pretty much, that is all for the current example. Creating a Dictionary with object and integer is not that difficult in C#. Here comes the whole code, if you need it for any reason:

Have a nice day! 😀

About

VBA Developer

Tagged with: , , , ,