System.Collections.Hashtable h=new System.Collections.Hashtable();
h.Add("key1","value1");
h.Add("key2","value2");
h.Add("key3","value3");
[.net] inverting a hashtable
I have run into a bit of a problem with my code. If I have a hashtable like this:
Can I make a new hashtable with the keys and the values inverted without hard-coding the values?
Just iterate over the table, and add the elements in reverse order to the other table.
Something like:
Something like:
using System.Collections;public static Hashtable MakeInverse( Hashtable h ) { Hashtable inverse = new Hashtable(); foreach( DictionaryEntry de in h ) { inverse.Add( h.value, h.key ); } return inverse;}
Quote:Original post by hplus0603
Just iterate over the table, and add the elements in reverse order to the other table.
Something like:using System.Collections;public static Hashtable MakeInverse( Hashtable h ) { Hashtable inverse = new Hashtable(); foreach( DictionaryEntry de in h ) { inverse.Add( h.value, h.key ); // if values are non-unique -- kablammo! } return inverse;}
That's not a terrific idea. The uniqueness of keys is guaranteed, but the uniqueness of the stored values is not. Depending on the application, in fact, it may well be the case that different keys have the same value. An inverted hashtable will therefore lose some information. If you care about that, use a different container type for the inverse hashtable to preserve any lost data.
Quote:Original post by kSquaredQuote:Original post by hplus0603
Just iterate over the table, and add the elements in reverse order to the other table.
Something like:using System.Collections;public static Hashtable MakeInverse( Hashtable h ) { Hashtable inverse = new Hashtable(); foreach( DictionaryEntry de in h ) { inverse.Add( h.value, h.key ); // if values are non-unique -- kablammo! } return inverse;}
That's not a terrific idea. The uniqueness of keys is guaranteed, but the uniqueness of the stored values is not. Depending on the application, in fact, it may well be the case that different keys have the same value. An inverted hashtable will therefore lose some information. If you care about that, use a different container type for the inverse hashtable to preserve any lost data.
no, it doesnt matter, because with the program I am making I can guarentee that it is unique. Thanks for the help!
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement