4

By creating a Dictionary<int,int> or List<KeyValuePair<int,int>> I can create a list of related ids.

By calling collection[key] I can return the corresponding value stored against it.

I also want to be able to return the key by passing in a value - which I know is possible using some LINQ, however it doesn't seem very efficient.

In my case along with each key being unique, each value is too. Does this fact make it possible to use another approach which will provide better performance?

Community
  • 1
  • 1
Peter Bridger
  • 9,123
  • 14
  • 57
  • 89
  • 2
    If keys and values are of the same type and distinct, you could add both associations (`k -> v`, `v -> k`) to the same dictionary, as long as you don't need to know which is which. – waldrumpus Sep 06 '12 at 10:22

2 Answers2

3

It sounds like you need a bi-directional dictionary. There are no framework classes that support this, but you can implement your own:

Bidirectional 1 to 1 Dictionary in C#

Community
  • 1
  • 1
ColinE
  • 68,894
  • 15
  • 164
  • 232
0

You could encapsulate two dictionaries, one with your "keys" storing your values and the other keyed with your "values" storing your keys.

Then manage access to them through a few methods. Fast and the added memory overhead shouldn't make a huge difference.

Edit: just noticed this is essentially the same as the previous answer :-/