Two way collection

  • Thread starter Thread starter Chris
  • Start date Start date
C

Chris

I need to do a mapping between two strings. I want to be able to look
up either string from the other. So if I know String A, I want to get
String B. If I know String B I want to get String A. I usually use
something like a hashtable, but that is one way. What should I use to
get a two way collection?

Thanks
Chris
 
Chris said:
I need to do a mapping between two strings. I want to be able to look
up either string from the other. So if I know String A, I want to get
String B. If I know String B I want to get String A. I usually use
something like a hashtable, but that is one way. What should I use to
get a two way collection?

Nothing built-in I can think of, but building your own wouldn't be too
hard - since both 'keys' and 'values' are Strings, just inherit from
Hashtable and override Add to also insert (b, a) whenever you insert
(a, b). Unless you need to know 'which way round' A and B were
originally supplied, in which case you'd need to do something like
inherit from DictionaryBase, and maintain two Hashtables internally,
one for 'original way round' mapping and one for 'the other way round'
mapping.
 
Larry said:
Nothing built-in I can think of, but building your own wouldn't be too
hard - since both 'keys' and 'values' are Strings, just inherit from
Hashtable and override Add to also insert (b, a) whenever you insert
(a, b). Unless you need to know 'which way round' A and B were
originally supplied, in which case you'd need to do something like
inherit from DictionaryBase, and maintain two Hashtables internally,
one for 'original way round' mapping and one for 'the other way round'
mapping.

I just hoped there was a way to do it w/o using two hashtables.

Thanks for the input.
Chris
 
Jeff Dillon said:
use an exhaustive search the other way around

If you aren't too worried about speed, you can use a StringCollection as a
base for something like the following collection class:

public class MyCollection : NameValueCollection
{
public string GetKeyByValue(string Value)
{
string[] keys = base.BaseGetAllKeys();
foreach (string key in keys) {
if (Array.IndexOf(base.GetValues(key), Value) >= 0) {
return key;
}
}
return null;
}
}

hth :)

Mythran
 
How about putting both:
(key=A, value=B)
and
(key=B, value=A) [if A<>B]

in the same hashtable? This way you could use the same hashtable to
lookup both ways (from A get B, from B get A)... mmm right?

-tom
 
Back
Top