Peter Bridger
Peter Bridger

Reputation: 9323

A two way KeyValuePair collection in C#

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?

Upvotes: 4

Views: 757

Answers (2)

logisticpeach
logisticpeach

Reputation: 58

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 :-/

Upvotes: 0

ColinE
ColinE

Reputation: 70170

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#

Upvotes: 3

Related Questions