An array of C#, PHP, and HTML programming articles, tutorials, and resources

Posts Tagged ‘ C# ’

Continuing from a previous post on Using C# Dictionary Collection, the next most common tasks is enumerate through every element in the Dictionary. To begin, each element in a Dictionary is a KeyValuePair. According to the C# documentation for Dictionary, the order of a KeyValuePair enumeration is not defined. Therefore, the KeyValuePair order may not be the same as the insertion (or Add) order. For that reason, we cannot use a for loop. Instead, a foreach loop is our solution. In this tutorial, I will demonstrate how to loop through the KeyValuePair, the Key, and the Value of a dictionary.

Foreach KeyValuePair

In this first example, we will be looping through the KeyValuePair. We can get both the key (as an int) and the value (as a string) from the KeyValuePair. Note that the type of the KeyValuePair must be declared in the foreach loop.

Dictionary myDictionary = new Dictionary();
myDictionary.Add(1, "ABC");
myDictionary.Add(2, "DEF");

foreach (KeyValuePair pair in myDictionary)
{
    int key = pair.Key;
    string value = pair.Value;
    Debug.WriteLine("Key: " + key.ToString() + " Value: " + value);
}

Foreach Key

In this second case, we will be looping through all Keys in the Dictionary. The Keys must be unique and in this example, the key is an integer.

Dictionary myDictionary = new Dictionary();
myDictionary.Add(1, "ABC");
myDictionary.Add(2, "DEF");

foreach (int key in myDictionary.Keys)
{
    Debug.WriteLine("Key: " + key.ToString());
}

Foreach Value

In this final case, we are looping through the Value of our dictionary. The value can be anything you define, but in our example, it is a string.

Dictionary myDictionary = new Dictionary();
myDictionary.Add(1, "ABC");
myDictionary.Add(2, "DEF");

foreach (string value in myDictionary.Values)
{
    Debug.WriteLine("Value: " + value);
}

At some point, every C# programmer deals with populating, selecting, and even deleting from a DataTable. A moderately advanced operation is transferring an entire single row from an original DataTable and inserting it into a new DataTable. My original thoughtprocess is the following:

DataTable originalTable = new DataTable();
originalTable.Columns.Add("id", typeof(int));
originalTable.Columns.Add("firstName", typeof(string));
originalTable.Columns.Add("lastName", typeof(string));
originalTable.Columns.Add("age", typeof(string));
originalTable.Columns.Add("gender", typeof(string));

DataRow dr = originalTable.NewRow();
dr["id"] = 1;
dr["firstName"] = "Victor";
dr["lastName"] = "Chen";
dr["age"] = 5;
dr["gender"] = "M";
originalTable.Rows.Add(dr);

dr = originalTable.NewRow();
dr["id"] = 2;
dr["firstName"] = "John";
dr["lastName"] = "Doe";
dr["age"] = 35;
dr["gender"] = "M";
originalTable.Rows.Add(dr);

dr = originalTable.NewRow();
dr["id"] = 3;
dr["firstName"] = "Jane";
dr["lastName"] = "Doe";
dr["age"] = 32;
dr["gender"] = "F";
originalTable.Rows.Add(dr);

DataTable newTable = originalTable.Clone();
newTable.Rows.Add(originalTable.Rows[1]);

Though the above example is long, lines 1 - 30 handle creating and populating the original DataTable (If you need explanation of how this works, check out Add Rows to a DataTable in C# tutorial). Line 32 creates a new DataTable by taking the structure of the original DataTable. In Line 33, we attempt to select Row 1 from the original DataTable and add it as a new row in the new DataTable. However, the above example above does not work. It will throw the runtime error below.

This row already belongs to another table.

The correct solution takes more lines of coding (and therefore more logic), but ultimately gets the job done. It involves using a DataRow’s ItemArray method to transfer a row’s data column by column through an object array, and inserting them column by column back into a new DataRow. See the example below:

DataTable originalTable = new DataTable();
originalTable.Columns.Add("id", typeof(int));
originalTable.Columns.Add("firstName", typeof(string));
originalTable.Columns.Add("lastName", typeof(string));
originalTable.Columns.Add("age", typeof(string));
originalTable.Columns.Add("gender", typeof(string));

DataRow dr = originalTable.NewRow();
dr["id"] = 1;
dr["firstName"] = "Victor";
dr["lastName"] = "Chen";
dr["age"] = 5;
dr["gender"] = "M";
originalTable.Rows.Add(dr);

dr = originalTable.NewRow();
dr["id"] = 2;
dr["firstName"] = "John";
dr["lastName"] = "Doe";
dr["age"] = 35;
dr["gender"] = "M";
originalTable.Rows.Add(dr);

dr = originalTable.NewRow();
dr["id"] = 3;
dr["firstName"] = "Jane";
dr["lastName"] = "Doe";
dr["age"] = 32;
dr["gender"] = "F";
originalTable.Rows.Add(dr);

DataTable newTable = originalTable.Clone();
DataRow newRow = newTable.NewRow();
newRow.ItemArray = originalTable.Rows[1].ItemArray;
newTable.Rows.Add(newRow);

Keeping consistent with our original example, lines 1-30 handle creating a DataTable. On line 32, create a DataTable. On Line 32, create a new DataRow. On Line 33, I select Row 1 from the Original DataTable, take it’s ItemArray, and transfer it to the newly created DataRow from Line 32. Finally, on line 34, I transfer newRow into the newTable.

If you have more than one row you would like to copy, merely repeat this process through a loop. Happy Coding!

Using C# Dictionary Collection

by Victor | November 19, 2008 in C# | 1 Comment

A Dictionary object in C# has become one of my recent favorites. Below are a few important aspects:

  1. Requires including System.Collections.Generic;
  2. Each entry in a Dictionary is a KeyValuePair (consisting of two objects: key and value)
  3. The key must be unique
  4. The value does not need to be unique
  5. Both the key and value can be any object (string, int, custom class, etc…)
  6. Retrieving a value via a key take close to O(1) time
  7. The order of a KeyValuePair enumeration is not defined

Next is an example of how to create and initialize a Dictionary object. Our Dictionary will have an integer and as a key and a string as a value.

Dictionary<int, string> myDictionary = new Dictionary<int, string>();

Now that we have our Dictionary datatype, we will add two values to the Dictionary. Note that at this point, intellisense knows the two expected types.

myDictionary.Add(1, "Victor");
myDictionary.Add(2, "Billy");

Finally, deleting an object is just as easy:

myDictionary.Remove(1);

And these are the basics to using a Dictionary collection!