Google


ADBRITE ads links
You are here: CodeIdol.com > C# > C# Cookbook, 2nd Edition > Generics > Using Foreach With Generic Dictionary Types

SAVE
Digg
Shown on del.icio.us del.icio.us
See Whos Talking About This on Technorati Technorati
I've Reddit reddit

Recipe 4.11. Using foreach with Generic Dictionary Types

Problem

You need to enumerate the elements within a type that implements System. Collections.Generic.IDictionary, such as System.Collections.Generic.Dictionary or System.Collections.Generic.SortedList.

Solution

The simplest way is to use the KeyValuePair structure in a foreach loop as shown here:

	// Create a Dictionary object and populate it.
	Dictionary<int, string> myStringDict = new Dictionary<int, string>();
	myStringDict.Add(1, "Foo");
	myStringDict.Add(2, "Bar");
	myStringDict.Add(3, "Baz");

	// Enumerate and display all key and value pairs.
	foreach (KeyValuePair<int, string> kvp in myStringDict)
	{
	    Console.WriteLine("key   " + kvp.Key);
	    Console.WriteLine("Value " + kvp.Value);
	}

Discussion

The nongeneric System.Collections.Hashtable (the counterpart to the System.Collections.Generic.Dictionary class), System.Collections.CollectionBase, and System.Collections.SortedList classes support foreach using the DictionaryEntry type as shown here:

	foreach (DictionaryEntry de in myDict)
	{
	    Console.WriteLine("key " + de.Key);
	    Console.WriteLine("Value " + de.Value);
	}

However, the Dictionary object supports the KeyValuePair<T,U> type when using a foreach loop. This is due to the fact that the GetEnumerator method returns an IEnumerator, which in turn returns KeyValuePair<T,U> types, not DictionaryEntry types.

The KeyValuePair<T,U> type is well suited to be used when enumerating the generic Dictionary class with a foreach loop. The DictionaryEntry object contains key and value pairs as objects, whereas the KeyValuePair<T,U> type contains key and value pairs as their original types, defined when creating the Dictionary object. This boosts performance and can reduce the amount of code you have to write, as you do not have to cast the key and value pairs to their original types.

See Also

See the "System.Collections.Generic.Dictionary Class," "System.Collections.Generic. SortedList Class," and "System.Collections.Generic.KeyValuePair Structure" topics in the MSDN documentation.


SAVE
Digg
Shown on del.icio.us del.icio.us
See Whos Talking About This on Technorati Technorati
I've Reddit reddit

You are here: CodeIdol.com > C# > C# Cookbook, 2nd Edition > Generics > Using Foreach With Generic Dictionary Types
   
Related tags







Popular Categories
Unix books and guides
AJAX popular information
C# language guides
Windows books and cookbooks
.......






© CodeIdol Labs, 2007