Creating a Bidirectional 1:1 Dictionary in C#
This article addresses the challenge of creating a bidirectional, one-to-one dictionary in C#. The requirement is a dictionary where each key has a unique value, and vice-versa, allowing lookups from both key and value.
Solution: A Custom BiDictionary Implementation
Instead of relying on standard C# dictionaries, a custom BiDictionaryOneToOne
class is the most effective solution. This class uses two internal dictionaries: one mapping TFirst
to TSecond
, and the other mapping TSecond
to TFirst
. This dual mapping ensures uniqueness and bidirectional access.
The BiDictionaryOneToOne
class includes several methods for efficient data management:
Add
, GetByFirst
, GetBySecond
, RemoveByFirst
, and RemoveBySecond
throw exceptions if the specified key or value isn't found. This provides clear error handling.TryAdd
, TryGetByFirst
, TryGetBySecond
, TryRemoveByFirst
, and TryRemoveBySecond
return true
on success and false
otherwise, avoiding exceptions for more flexible error handling.Count
returns the number of key-value pairs, and Clear
removes all entries.This custom BiDictionaryOneToOne
class provides a robust and efficient solution for managing bidirectional 1:1 relationships in C#. Its clear error handling and comprehensive functionality make it ideal for various data management scenarios requiring unique key-value pairings with efficient lookup capabilities from either side.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3