Wednesday 1 February 2012

Dictionaries in .Net



Dictionaries are a kind of collection that store items in a key-value pair fashion.

System.Collections namespace

 Dictionary type in the base class library is one of the most important ones you need to use for your C# programs. It is an implementation of a hashtable, which is an extremely efficient way to store keys for lookup. The Dictionary in .NET is well-designed, and this section shows lots of ways you can use it.
Dictionary
We try to reference items in a table directly by doing arithmetic operations to transform keys into table addresses.Sedgewick, p. 587
Program that uses Dictionary [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
 // Use the dictionary.
 Dictionary<string, int> dict = new Dictionary<string, int>();
 dict.Add("cat", 1);
 dict.Add("dog", 4);

 Console.WriteLine(dict["cat"]);
 Console.WriteLine(dict["dog"]);
    }
}

Output

1
4
Description. This simple program demonstrates how the Dictionary can be used with type parameters to store keys and values of specific types. You can store and then retrieve keys and values from the Dictionary collection.

No comments:

Post a Comment