Home Page

Category: Arrays and Lists

Click here to download the sample source code for this Dictionary lab exercise 

There is another useful C# class that I would like to cover as part of the Arrays and Lists lessons.  This class is called the .  The Dictionary is also part of the System.Collections.Generic namespace but it has a different purpose than a List object.  The Dictionary object is useful when you need to store key/value pairs in memory.  For example if you want to store attributes about a web application user such as ip address, first name, last name, userid you could setup a Dictionary as such:

Key          Value
—-          ——
ip              129.168.29.38
fname      Billy
lname      Gibbons
uid           bgibbons

You could access the last name of the user by using the syntax mydictionary[”lname”].  In a Dictionary, the key is always unique.  Let’s do an example together.  Create a new web form Default3.aspx and put a Button and a TextBox on the form.  Change the Text of the Button to “Dictionary”.  Double click the Button to create the event handler and put:

 

Dictionary<string, string> mydictionary =
    new Dictionary<string, string>();

mydictionary["ted"] = "kolovos";
mydictionary["mark"] = "jenkins";

TextBox1.Text = "The item at position ted is: " +
    mydictionary["ted"];

Make sure you have System.Collections.Generic in your namespaces at the top of the code.  In this example above, notice that inside the < > following the Dictionary type declaration I had to specify 2 things.  The first is the data type for the key of the Dictionary which is string.  The second is the data type for the value of the Dictionary which happens to also be string.  The data type for the key and value can be anything you want.

I put an item into the Dictionary using the syntax mydictionary[”ted”] and the assignment operator.  Then when I want to later determine what is stored inside the Dictionary with the key of “ted” I use the exact same syntax with the square brackets.  Remember that the key in a Dictionary is always unique.  Also note that if you are using strings as the Dictionary key, it is case sensitive, so mydictionary[”ted”] is a different place in the Dictionary versus mydictionary[”Ted”].  Because of this sometimes programmers change the key to upper case before loading data into the Dictionary and when accessing the contents to avoid invalid searches.

The Dictionary object is idea when you want to store key/value pairs or perform searches based on a key value.  If you simply want to store a list of objects and are not looking for any search capability, use the List object instead.

The Dictionary object has a method called ContainsKey which can search the Dictionary to determine if an item exists.  Here is an example that shows how it can be used:

 

Dictionary<string, string> mydictionary =
    new Dictionary<string, string>();

mydictionary["ted"] = "kolovos";
mydictionary["mark"] = "jenkins";

if (mydictionary.ContainsKey(txtFirstname.Text))
    txtOutput.Text = mydictionary[txtFirstname.Text];
else
    txtOutput.Text = "That doesn't exist";

Refer to the Default3.aspx file sample source code provided as part of Lab3_csharpuniversity.zip to see the web form for this example.

Category: Arrays and Lists

Click here to download the sample source code for this Lists lab exercise 

Now that we have seen how Arrays work, let’s take a look at a more versatile C# object: the class.  This class is found in the System.Collections.Generic namespace.  I like to think of the List class as a fancy Array; it is very similar to an Array, with more functionality and it is more dynamic.  With a List object, you don’t have to define the size of the List ahead of time.  It can grow dynamically based on how many items you put into it.  Just that characteristic alone, makes it easier to use for a lot of C# programmers.  If you know ahead of time, how many items you need to store in a list, you may be able to use the Array, but if you are unsure, the List object may suit you better.  Let’s see an example.

Create a new web form called Default2.aspx in your Lab3 project.  Click here to watch an example video in case you forgot how to add a new web form.  Drag a Button onto the form and change the Text to “List of integers”.  Drag a TextBox onto the form and make it MultiLine.  Double click the Button to create the event handler and put the following:

 

List<int> mylist = new List<int>();

mylist.Add(33);
mylist.Add(55);
mylist.Add(10);
mylist.Add(509);

foreach (int myvar in mylist)
{
    TextBox1.Text += myvar.ToString() + "\r\n";
}

In the using statements at the top of the source code file, make sure that you have “using System.Collections.Generic” listed somewhere, otherwise you will get an error when you try to run the project and the compiler may complain it cannot find the List class.

To declare a List, I used the syntax List<int> mylist = new List<int>();  The data type is List and following the data type is an expression that tells C# what kind of type you plan to hold in the List.  In my case, my List hold int numbers so I placed that inside the < >.  Notice on the right side of the assignment operator = that I had to put parentheses after List<int>.  In the later lessons dedicated to coding and calling C# classes I talk more in detail about why this is necessary.

Putting items into the List is easy, you use the Add method mylist.Add(10);  Notice that I didn’t have to declare how big my List is, I can call the Add method as many times as I like.

To access the items in the List you can use a similar syntax to that of Arrays mylist[0] using the index number.  In the example above I used a slightly different approach which is the C# loop.  The foreach loop is a special kind of loop in C# that can easily loop through Collections.  Collections are special types that facilitate this kind of iteration.  The List class is a type of Collection.

With the syntax foreach (int myvar in mylist) we can talk about each part of the foreach syntax separately.  Inside the parentheses there are 4 parts to the foreach expression.  The first part specifies the data type “int” that we are planning to read from the Collection.  The second part “myvar” is simply a temporary variable that will hold the contents of the List each time the loop iterates.  The third part is the keyword “in”.  Finally, the fourth part is the name of the Collection that you want to loop through which in this case is “mylist”, the List class.  This loop will start at the beginning of the List starting with the first item that you added into the List and end with the last item which was added to the List.  I could have also used a for loop instead of the foreach loop:

 

for (int i = 0; i < mylist.Count; i++)
{
    TextBox1.Text += mylist[i].ToString() + "\r\n";
}
Next Page »