Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Could someone please explain dictionaries in c#??

Needing help

Best Answer

  • edited November 2020 Accepted Answer

    So a dictionary is basically a collection of keys and values. The keys can be used to access the values attached to them once in the dictionary. To add something to the dictionary first it needs to be the same type as the value and have a unique ID. So for example lets say I have created an animal class with a a value for ID, type, speed, and health. We want to use the ID which is an integer for they key and for the value we want to use the Animal object itself. Yo create a dictionary of this nature you would write this:

    Dictionary<int, Animal> animals = new Dictionary<int, Animal>();

    To add to the dictionary we use the add method so lets say I want to add a Animal object named dog to this we can put this:

    animals.add(dog.ID, dog);

    If I want to refrence something I use the key so to find dog that would look like

    Animal animal1 = animals[1];

    to search with a foreach loop:

    foreach(KeyValuePair<int, Animal> a in animals )

    {

    Console.WritLine ("ID = " + a.Key)

    //to actually store the object we could say

    Animal animal = a.Value;/*this works because the value of a is Animal, and now you can access animal.ID, animal.health, etc. for example:

    Console.WriteLine("This is a " + animal.type + ", and it is " +animal. speed + " fast" + " and it has " + animal.health + " health")

    }

    if you only want to loop through just values or just keys as well:

    for Value: foreach(Animal<int, Animal> a in animals )

    for key: foreach(int<int, Animal> a in animals )

    A few things to keep in mind are that a Key and a value can be of any type I just used int and animal here, IDs must be unique in a dictionary, and a dictionary uses Sytems.Collections.Generic so be sure to add that,.

    This video probably explains better than I did: https://www.youtube.com/watch?v=fMjt6ywaSow

Sign In or Register to comment.