DictionarymyDict = new Dictionary (); myDict.Add("apple", 10); myDict.Add("banana", 5); myDict.Add("orange", 7); int numApples = myDict["apple"]; Console.WriteLine("Number of apples: " + numApples);
class Animal { public string Name { get; set; } public int Age { get; set; } } class AgeComparer : IEqualityComparerIn this example, we create a custom Animal class with Name and Age properties. We then create a separate class AgeComparer that implements the IEqualityComparer interface. This enables us to compare the animals in the dictionary based on their age property. We create a new Dictionary object called zoo and pass our custom AgeComparer to the constructor. We add three animal-location pairs to the dictionary and then iterate over all key-value pairs using a foreach loop. We create a string called locationOfOldAnimals and add the location of all animals over 10 years old to it. Finally, we print the string to the console. In conclusion, C# Dictionary is a powerful data structure that enables storing and manipulating data in key-value pairs. It is part of the System.Collections.Generic namespace in the .NET Class Library.{ public bool Equals(Animal x, Animal y) { return x.Age == y.Age; } public int GetHashCode(Animal obj) { return obj.Age.GetHashCode(); } } Dictionary zoo = new Dictionary (new AgeComparer()); zoo.Add(new Animal() { Name = "Lion", Age = 10 }, "Africa"); zoo.Add(new Animal() { Name = "Tiger", Age = 15 }, "Asia"); zoo.Add(new Animal() { Name = "Penguin", Age = 5 }, "Antarctica"); string locationOfOldAnimals = ""; foreach (KeyValuePair kvp in zoo) { if (kvp.Key.Age > 10) locationOfOldAnimals += kvp.Value + ", "; } Console.WriteLine("Locations of old animals: " + locationOfOldAnimals);