Skip to main content

Dictionaries in .Net



Namespace: System.Collections

Dictionaries are meant to store data in Key/Value pair.
Dictionary class supports the Key/Value pair collection.

Most basic Implementation is HashTable.
HashTable h = new HashTable();
h.add(“mubbasher@ymail.com”, “Mubbasher Mukhtar”);
h[“mubbasher@ymail.com”] = “Mukhtar, Mubbasher”;
Console.WriteLine(h[“mubbasher@ymail.com”]);

To iterate items in Dictionary:

foreach(DictionaryEntery entry in h)
                Console.WriteLine( entry.Value);

All Dictionary classes inherit from IDictionary interface. And intern IDictionary interface inherits from ICollection Interface.

Inheritance Sequence:
IEnumerator  IEnumerable ICollection IDictionary

Important properties of the IDictionary interface:
Name
Description
Count
Gets the number of elements contained in the ICollection. (Inherited from ICollection.)
IsFixedSize
Gets a value indicating whether the IDictionary object has a fixed size.
IsReadOnly
Gets a value indicating whether the IDictionary object is read-only.
IsSynchronized
Gets a value indicating whether access to the ICollection is synchronized (thread safe). (Inherited from ICollection.)
Item
Gets or sets the element with the specified key.
Keys
Gets an ICollection object containing the keys of the IDictionary object.
SyncRoot
Gets an object that can be used to synchronize access to the ICollection. (Inherited from ICollection.)
Values
Gets an ICollection object containing the values in the IDictionary object.

IDictionary Methods:
Name
Description
Add
Adds an element with the provided key and value to the IDictionary object.
Clear
Removes all elements from the IDictionary object.
Contains
Determines whether the IDictionary object contains an element with the specified key.
CopyTo
Copies the elements of the ICollection to an Array, starting at a particular Array index. (Inherited from ICollection.)
GetEnumerator
Returns an IDictionaryEnumerator object for the IDictionary object.
GetEnumerator
Returns an enumerator that iterates through a collection. (Inherited from IEnumerable.)
Remove
Removes the element with the specified key from the IDictionary object.
HashTable also supports the following two methods:
ContainsKey
Determines whether the Hashtable contains a specific key.
ContainsValue
Determines whether the Hashtable contains a specific value.


Understanding Equality:
HashTable is a special type of Dictionary class that uses an integral value (a hash value) as its key. HahsTable uses hash value to speedup searching. Hash value is obtained by the GetHash() method of the object that return a unique hash value identifying the object.

If one is using an object as a key for the HashTable, Then one must override the GetHashCode() method that will return a Hash code to be used as key value.

public class Fish
{
    public string fname;
    public Fish(string pFishName)
    {
        fname=pFishName;
    }
   
    public override int GetHashCode()
    {
        return fname.GetHashCode();
    }
}

Fish fishA = new Fish(“blue fish”);
Fish fishB = new Fish(“blue fish”);
Hashtable[fishA] = “New fish”;
Hashtable[fishB] = “New fishB”;

But the Hashtable.Count() will return two; even we have overridden the GetHashCode method. We will also have to override the Equals method to uniquely identify the object.

public override bool Equals(object obj)
{
        return fname == ((Fish)obj).fname;
}

For Uniqueness of a key for a hash table, Hash code and Instances should not be equal.

Using IEqualtyComparer Interface:
                HashTable supports a constructor that accepts a IEqualityComparer interface. IEqualityComparaer contains two methods, GetHashCode and Equals. Following CaseInsensitveComparer can be used for HashTables to make case insensitive comparisons.

public class InsensitiveComparer: IEqualityComparer
{
                public int GetHashCode(object obj)
                {
                                return obj.ToString().ToLowerInverient().GetHashCode();
                }
                public new bool Equals(object a, object b)
                {
return a.ToString().ToLowerInvarient() ==  b.ToString().ToLowerInvarient();
                }
}

SortedList:
HashTable displays items by the order of HashCode. SortedList automatically sorts items on basis of key. When items are being added they are automatically sorted. It inherits from IDictionary.

Default Sort method used by SortedList sorts items in Ascending order. One can specify his own IComparer interface in one of the SortedList constructor to specify different sorting order.

SortedList Members:
Name
Description
Capacity
Gets or sets the capacity of a SortedList object.
Count
Gets the number of elements contained in a SortedList object.
IsFixedSize
Gets a value indicating whether a SortedList object has a fixed size.
IsReadOnly
Gets a value indicating whether a SortedList object is read-only.
IsSynchronized
Gets a value indicating whether access to a SortedList object is synchronized (thread safe).
Item
Gets and sets the value associated with a specific key in a SortedList object.
Keys
Gets the keys in a SortedList object.
SyncRoot
Gets an object that can be used to synchronize access to a SortedList object.
Values
Gets the values in a SortedList object.

SortedList Methods:

Name
Description
Contains
Determines whether a SortedList object contains a specific key.
ContainsKey
Determines whether a SortedList object contains a specific key.
ContainsValue
Determines whether a SortedList object contains a specific value.
GetByIndex
Gets the value at the specified index of a SortedList object.
GetKey
Gets the key at the specified index of a SortedList object.
GetKeyList
Gets the keys in a SortedList object.
GetValueList
Gets the values in a SortedList object.
IndexOfKey
Returns the zero-based index of the specified key in a SortedList object.
IndexOfValue
Returns the zero-based index of the first occurrence of the specified value in a SortedList object.
Remove
Removes the element with the specified key from a SortedList object.
RemoveAt
Removes the element at the specified index of a SortedList object.
SetByIndex
Replaces the value at a specific index in a SortedList object.
Synchronized
Returns a synchronized (thread-safe) wrapper for a SortedList object.
TrimToSize
Sets the capacity to the actual number of elements in a SortedList object.

List Dictionary:
At times we have smaller collection of nearly ten items, where HashTable have a bit overhead in performance. To bridge the gap .Net framework provides ListDictionary that have the same methods and Properties as HashTable but saves items in an array internally.

HybridDictionary:
At times we don’t know how large a collection could be, So we can use HybridDictionary, that stores items in an array initially and when collection, it automatically converts the collection into a HashTable. It also provides the same methods and properties as HashTable.

OrderedDictionary:
                It is much like the HashTable, but keeps the items in the order they are being added.
Extra properties provided by OrderedDictionary are:
Item: Access items by index.

Methods
Insert: Inserts Key/value pair at a specific location.
RemoveAt: Removes Item from a specific location.

Comments

Popular posts from this blog

Culture Information and Localization in .NET

Namespace: System.Globalization CultureInfo Class:                 It provides information like the Format of numbers and dates, Culture’s Calendar, Culture’s language and sublanguage (if applicable), Country and region of the culture. The Basic use of CultureInfo class is shown here: • How string Comparisons are performed • How Number Comparison & Formats are performed • Date Comparison and Formats. • How resources are retrieved and used. Cultures are grouped into three categories: Invariant Culture : It’s Culture Insensitive. It can be used to build some trial application. It can be also used to build an application with hard-coded expiry date that ignores cultures. But using it for every comparison will be incorrect and inappropriate. Neutral Culture : English(en), Frensh(fr), and Spanish(sp). A neutral culture is related to language but it’s not related to specific regi...

Concept of App Domain in .Net

Creating Application Domains: Application domain is just like process, provides separate memory space, and isolates from other code. But it’s quite light weight. It also provides the following advantages: 1-       Reliability : If a domain crashes, it can be unloaded. Hence doesn’t affect the other assemblies. 2-       Efficiency : Loading all assemblies in one domain can be cumbersome and can make the process heavy but Appdomains are efficient in this manner. Important properties of AppDomain: ApplicationIdentity , ApplicationTrust , BaseDirectory , CurrentDomain , DomainManager , DomainDirectory , Evidence , FriendlyName , ID , RelativeSearchPath , SetupInformation , ShadowCopyFiles . Important methods of AppDomain: ApplyPolicy , CreateCOMInstanceFrom , CreateDomain , CreateInstance (Assembly). To create an AppDomain: AppDomain adomain = AppDomain.CreateDomain(“D”); To execute an assembly:...

Asynchronous Execution in ASP.NET

Asynchronous Execution: Two ways either implement IHTTPAsyncHandler interface or in ASP.NET 2.0 set <%@ Page Async=”true” %>. The second option implements IHTTPAsyncHandler interface automatically for the page when parsed or compiled. AddOnPreRenderCompleteAsync ( new BeginEventHandler(BeginTask), new EndEventHandler(EndTask)); AddOnPreRenderCompleteAsync() shoud be called in Page_load. The BeginEventHandler and EndEventHandler are delegates defined as follows: IAsyncResult BeginEventHandler( object sender, EventArgs e, AsyncCallback cb, object state) void EndEventHandler( IAsyncResult ar) AsyncProcess starts and completes between PreRender and PreRenderComplete. Other way to perform Async Task is using AsyncPageTask structure. It also allows multiple tasks to execute simultaneously. void Page_Load (object sender, EventArgs e) { PageAsyncTask task = new PageAsyncTask( new BeginEventHandler(BeginTask), new EndEventH...