Tech Off Thread

5 posts

How do you output the contents of a Dictionary class?

Back to Forum: Tech Off
  • User profile image
    complete

    This is kind of a follow up to this post:

    http://channel9.msdn.com/Forums/TechOff/How-To-Modify-An-Element-in-the-Dictionary-Class

    Once I have the data nice and sorted like I want it, how do I spew it back out in the nice and ordered fashion?

    In C#, how do you output the contents of a Dictionary class?

    Once you have loaded a Dictionary class with keys and values, how do I cycle through them and output the individual values in a foreach loop?

     

  • User profile image
    blowdart

    Something like

     

    foreach (var key in dictionary.Keys)
    {
        var value = dictionary[key];
        // Output value however you want
    }

     

  • User profile image
    felix9

    what's so difficult about foreach ?

                foreach (var i in dict) {
                    var key = i.Key;
                    var val = i.Value;
                }
    

    wait a minute, you want to sort a dictionary ?? are you sure dictionary is the data structure you want ?

  • User profile image
    evildictait​or

    If you want to sort it, that's easy too

    foreach(var key in dictionary.Keys.SortBy( ... ) )
    {
      var value = dictionary[key];
      // output value however you want.
    }

  • User profile image
    wkempf

    There's a SortedDictionary that is implemented using a tree so that the dictionary is sorted by the key. There's tradeoffs between using trees and hashtables, so be sure which data structure you really want before blindly switching. With a SortedDictionary you'd just use foreach to iterate over the KeyValuePair items in the dictionary, or use the Keys or Values properties to iterate over just the key or just the value.

Comments closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.