how can I create a hash of hash (or key with multiple values)

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • digitech
    New Member
    • Mar 2009
    • 2

    how can I create a hash of hash (or key with multiple values)

    Hi,

    In perl I can create a hash of hash which would have something like

    $MYHASH{'USER1' }{'SPORT'}{'FOO TBALL'} =1

    $MYHASH{'USER1' }{'SPORT'}{'TEN NIS'} =1

    http://docstore.mik.ua/orelly/perl/prog3/ch09_04.htm shows a type of example on the perl page.

    This way I can loop through the users and the sports and find out what sports they are associated to.

    How can I create a similar stucture in c Sharp, I have been looking at hashtables but they only show my key <=> values. Where I need to have a key with an array of values that I can index in on.

    Can anyone help here please or point me to some examples ?

    Thanks in advance.
  • PRR
    Recognized Expert Contributor
    • Dec 2007
    • 750

    #2
    If you are looking for collection that allows multiple values per key then you can go in for NameValueCollec tion
    Code:
    NameValueCollection mycol = new NameValueCollection();
                mycol.Add("1", "1");
                mycol.Add("1", "2");
                mycol.Add("1", "3");
                mycol.Add("1", "4");
    
                foreach (string s in mycol.GetValues(0))
                {
                    Console.WriteLine(mycol[s]);
                }

    Comment

    • digitech
      New Member
      • Mar 2009
      • 2

      #3
      Thanks this is great, I noticed on the link that NameValueCollec tion is for 2008 only is there an eqilavant way of doing this for VS 2005 ?

      Comment

      • vekipeki
        Recognized Expert New Member
        • Nov 2007
        • 229

        #4
        It exists in VS2005 also: NameValueCollec tion.

        But Hashtable also implements IEnumerable for DictionaryEntry objects, so you can also write:

        Code:
        foreach (DictionaryEntry entry in myHashtable)
        {
           Console.WriteLine("Key = {0}, Value = {1}", entry.Key, entry.Value);
        }
        There is also a generic Dictionary<TKey ,TValue> you can use, which implements IEnumerable for KeyValuePair<TK ey,TValue> items.

        Comment

        Working...