Retrieve multiple keys for a given value from a generic dictionary
Retrieving a value based on a given key from a .NET generic dictionary is very simple using indexer syntax. However, since there may be multiple keys with the same value, retrieving the key corresponding to a specified value may be more challenging.
Introduction to BiDictionary data structure
To solve this problem, the BiDictionary data structure was developed, allowing bidirectional mapping between keys and values. It maintains two internal dictionaries:
Implementation details
The BiDictionary class provides methods to add key-value pairs and retrieve values based on either key type. For example:
<code class="language-csharp">BiDictionary<int, string> greek = new BiDictionary<int, string>(); greek.Add(1, "Alpha"); greek.Add(2, "Beta"); greek.Add(5, "Beta"); IList<int> betaKeys = greek["Beta"]; // 返回 [2, 5]</code>
This implementation uses an empty list as the default return value for non-existent keys, ensuring that you always receive a list, even if it is empty.
Customizable indexer
For convenience, BiDictionary includes customizable indexers that provide direct access to the internal dictionary based on the calling key type. This simplifies access to values by allowing you to use indexer syntax:
<code class="language-csharp">BiDictionary<int, string> greek = new BiDictionary<int, string>(); greek.Add(1, "Alpha"); greek.Add(2, "Beta"); string secondGreek = greek[2]; // 返回 "Beta"</code>
Example usage
The provided code demonstrates the functionality of BiDictionary:
<code class="language-csharp">BiDictionary<int, string> greek = new BiDictionary<int, string>(); greek.Add(1, "Alpha"); greek.Add(2, "Beta"); greek.Add(5, "Beta"); ShowEntries(greek, "Alpha"); // 打印 "Alpha: [1]" ShowEntries(greek, "Beta"); // 打印 "Beta: [2, 5]" ShowEntries(greek, "Gamma"); // 打印 "Gamma: []"</code>
This example demonstrates how to retrieve the key corresponding to a given value, and it handles the case of non-existent values gracefully by returning an empty list.
The above is the detailed content of How Can I Retrieve Multiple Keys Associated with a Single Value in a Generic Dictionary?. For more information, please follow other related articles on the PHP Chinese website!