Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bijective Dictionary /Map in C# [duplicate]

Tags:

c#

dictionary

Is there a bijective dictionary in.NET that efficiently stores Key/Values pairs, where both keys and values are distinct, so a bijective mapping (i.e. TryGetValue/TryGetKey) is possible? The naive approach would be to have two internal dictionaries: A key-value and a value-key dictionary, but this is not efficient in terms of memory.

like image 407
Rauhotz Avatar asked Feb 20 '09 15:02

Rauhotz


2 Answers

I don't believe there's one in .NET. Depending on the key/value types, I'm not sure that using two dictionaries is likely to cause that much of an efficiency loss: it's what I'd do until I saw a problem, based on the fact that it's simple.

In fact, it's very simple as I've already implemented it in another Stack Overflow answer. I'll see if I can find it...

EDIT: I found two:

  • One of mine
  • Another based on mine, but more fully developed with Remove etc.
like image 130
Jon Skeet Avatar answered Nov 20 '22 04:11

Jon Skeet


Essentially you want 2 Sets that reference the same binary element. You will always have the overhead of the references to both elements, but you'd have that either way. Each set would need a different comparer, but that's little overhead. Since you referencing the same element, in both set, you don't have 2 copies.

HashSet HashSet Methods/Members

like image 2
sfossen Avatar answered Nov 20 '22 04:11

sfossen