Sunday 10 May 2015

Dictionary

Dictionary<TKey, TValue> is a key value pair collection, where you specify the type for both the key and the value.

to get started, let's create an oldschool console application with a main

dotnet new console -n pav.dictionaryExample --use-program-main

with our console application created open it in ms code

code ./pav.dictionaryExample 

and that should open your newly created dotnetcore project.

in our example let's create a person class,  we are going 


namespace DictionaryExample
{
    class Person
    {
        public string Name { get; set; }
        public DateTime BirthDate { get; set; }

        public Person(string Name, DateTime BirthDate) {
            this.Name = Name;
            this.BirthDate = BirthDate;
        }

        public int GetAge() {
            DateTime today = DateTime.Today;
            int age = today.Year - BirthDate.Year;
            return BirthDate > today.AddYears(-age) ? --age : age;
        }

        public override string ToString() { return $"{Name} is {GetAge()}"; }
    }

    class Program {
        static void Main(string[] args) {
            var d = new Dictionary<string, Person>();

            var p1 = new Person("Pavel", new DateTime(1984, 01, 31));
            var p2 = new Person("Tomek", new DateTime(1988, 08, 28));
            var p3 = new Person("Magda", new DateTime(1984, 06, 28));

            d.Add(p1.Name, p1);
            d.Add(p2.Name, p2);
            d.Add(p3.Name, p3);

            foreach (KeyValuePair<string, Person> de in d)
                Console.WriteLine("{0}: {1}", de.Key, de.Value.ToString());


            //print out a direct member of the dictionary by itS defined key.
            Console.WriteLine (d["Tomek"]);
        }
    }
}



if you run the above code you get the following:



if you want to remove and element by it's key you can simply call


d.Remove("Pavel");


if your collection doesn't contain this key nothing happens which is nice, if you want to retrieve an item using the key, it's just as simple.


            Console.WriteLine("get an object by a non-existent key");
            Console.WriteLine (d["marin"]);


Except for the exception that gets thrown if you query for a key that doesn't exist.



which is why it is always a good practice to first check is the key is contained in the collection


            Console.WriteLine("get an object by a non-existent key");
            if(d.ContainsKey("marin"))
                Console.WriteLine (d["marin"]);
             

The dictionary class also contains a containsValue method which works the same way, but obviously would have a performance impact. They key property is optimized for retrieving data.


            var p4 = new Person("Marin", new DateTime(1983, 11, 02));
            if (!d.ContainsValue(p4))
                d.Add(p4.Name, p4);


one caveat is that searching by value is not exactly efficient, search by key when you can.