C#
  Home arrow C# arrow Page 2 - Generics, Dictionaries, and More
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Silverlight  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
ASP Web Hosting  
ASP.NET Web Hosting 
Windows Web Hosting
 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C#

Generics, Dictionaries, and More
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 3
    2008-12-24

    Table of Contents:
  • Generics, Dictionaries, and More
  • 4.10 Using foreach with Generic Dictionary Types
  • 4.11 Constraining Type Arguments
  • 4.12 Initializing Generic Variables to Their Default Values

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Generics, Dictionaries, and More - 4.10 Using foreach with Generic Dictionary Types


    (Page 2 of 4 )

    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>()
         
    { { 1, "Foo" }, { 2, "Bar" }, { 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 supportforeachusing theDictionaryEntrytype, as shown here:

      Hashtable myHashtable = new Hashtable()
         { { 1, "Foo" }, { 2, "Bar" }, { 3, "Baz" } };
      foreach (DictionaryEntry de in myHashtable)
      {
        
    Console.WriteLine("key   " + de.Key);
        
    Console.WriteLine("Value " + de.Value);
        
    Console.WriteLine("kvp " + de.ToString
    ());
     
    }

    However, theDictionaryobject supports theKeyValuePair<T,U>type when using aforeachloop. This is due to the fact that theGetEnumeratormethod returns anIEnumerator, which in turn returnsKeyValuePair<T,U>types, notDictionaryEntrytypes.

    TheKeyValuePair<T,U>type is well suited to be used when enumerating the genericDictionaryclass with aforeachloop. TheDictionaryEntryobject contains key and value pairs as objects, whereas theKeyValuePair<T,U>type contains key and value pairs as their original types, defined when creating theDictionaryobject. 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

    The “System.Collections.Generic.Dictionary Class,” “System.Collections.Generic. SortedList Class,” and “System.Collections.Generic.KeyValuePair Structure” topics in the MSDN documentation.

    More C# Articles
    More By O'Reilly Media


       · This article is an excerpt from the book "C# 3.0 Cookbook, Third Edition," published...
     

    Buy this book now. This article is excerpted from chapter four of the C# 3.0 Cookbook, Third Edition, written by Jay Hilyard and Stephen Teilhet (O'Reilly, 2008; ISBN: 059651610X). Check it out today at your favorite bookstore. Buy this book now.

    C# ARTICLES

    - Coding a CRC-Generating Algorithm in C
    - Cyclic Redundancy Check
    - Handling Methods and Functions
    - Destroying Objects in C#
    - Creating Objects in C-Sharp
    - Classes and Objects
    - Programming Languages: Managed versus Native
    - LINQ-to-MySQL with DbLinq in C#
    - Working with Dates and Times in C#
    - Generics, Dictionaries, and More
    - More About Generics
    - Working with C# Collections
    - Generics
    - C# and XML
    - Pointers and Arrays in C#





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 1 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek