Tech Off Thread

5 posts

Forum Read Only

This forum has been made read only by the site admins. No new threads or comments can be added.

How do you output the contents of a Dictionary class?

Back to Forum: Tech Off
  • User profile image

    This is kind of a follow up to this post:

    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

    Something like


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


  • User profile image

    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

    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

    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.

Conversation locked

This conversation has been locked by the site admins. No new comments can be made.