Posted on 18th January 2012No Responses
Basics: Dictionary (Create, sort + comparison with Hashtable)

back_to_basics

Dictionaries are my favourite structure to populate drop down lists.

A method that returns a Dictionary will in fact return a list of paired values with keys. In the case of a drop down list, where you will be after some text to be displayed and some value to be stored, the dictionary value will be your drop down list text and the dictionary key will be your drop down list value.

So, in the following example,

private Dictionary<string, string> Build_Dictionary_Of_Relevant_Workshops()

I have a private method that will return a Dictionary where both the key and value will be of type string (this, of course, is not imperative). Now, in order to bind this dictionary to a drop down list, I will simply do the following:

DropDownList ddlListOfWorkshops = new DropDownList();

Dictionary<string, string> ddlDataSource = Build_Dictionary_Of_Relevant_Workshops();
ddlListOfWorkshops.DataSource = ddlDataSource;
ddlListOfWorkshops.DataTextField = “Value”;
ddlListOfWorkshops.DataValueField = “Key”;
ddlListOfWorkshops.DataBind();

The compiler will know that the text values that are being assigned to the DataTextField and DataValueField of the DropDownList refer to the value and key of the Dictinary pairs. Remember to .DataBind() and you’re good to go.

NOTE: Helpful post about the Dictionary data structure “here” by kirupa.com.

Also, here’s a solution on the sorting issue (how to sort a dictionary) taken from  stackoverflow.

System.Collections.Generic.Dictionary<string, int> myDict = new Dictionary<string, int>();
myDict.Add(“one”, 1);
myDict.Add(“four”, 4);
myDict.Add(“two”, 2);
myDict.Add(“three”, 3);

var sortedDict = (from entry in myDict orderby entry.Value ascending select entry).ToDictionary(pair => pair.Key, pair => pair.Value);

Also, Dictionary Class VS Hashtable Class.
Dictionary is a generic type, Hashtable is not. That means you get type safety with Dictionary, because you can’t insert any random object into it, and you don’t have to cast the values you take out. Hashtable uses Object to hold things internally (which is the only non-generic way to do it) so it would also have to box/unbox. Because of that, the Dictionary class, like all generic collections which do not need to box/unbox, is a lot faster

Comments
Leave a Response
XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>