Get multiple keys for a specific value in a generic dictionary
In .NET, retrieving the value associated with a key in a generic dictionary is very simple. However, determining the key of a given value is not easy, especially when multiple keys may correspond to the same value.
Question
Consider the following code snippet:
<code class="language-csharp">Dictionary<int, string> greek = new Dictionary<int, string>(); greek.Add(1, "Alpha"); greek.Add(2, "Beta"); int[] betaKeys = greek.WhatDoIPutHere("Beta"); // 预期结果为单个 2</code>
The goal is to get an array containing keys that map to the value "Beta".
Solution
We can create a custom two-way dictionary that is able to retrieve keys and values:
<code class="language-csharp">using System; using System.Collections.Generic; using System.Linq; class BiDictionary<TFirst, TSecond> { private IDictionary<TFirst, IList<TSecond>> firstToSecond = new Dictionary<TFirst, IList<TSecond>>(); private IDictionary<TSecond, IList<TFirst>> secondToFirst = new Dictionary<TSecond, IList<TFirst>>(); public void Add(TFirst first, TSecond second) { IList<TSecond> seconds; IList<TFirst> firsts; if (!firstToSecond.TryGetValue(first, out seconds)) { seconds = new List<TSecond>(); firstToSecond[first] = seconds; } if (!secondToFirst.TryGetValue(second, out firsts)) { firsts = new List<TFirst>(); secondToFirst[second] = firsts; } seconds.Add(second); firsts.Add(first); } public IEnumerable<TSecond> GetByFirst(TFirst first) { IList<TSecond> list; return firstToSecond.TryGetValue(first, out list) ? list : Enumerable.Empty<TSecond>(); } public IEnumerable<TFirst> GetBySecond(TSecond second) { IList<TFirst> list; return secondToFirst.TryGetValue(second, out list) ? list : Enumerable.Empty<TFirst>(); } }</code>
To use this two-way dictionary, we can replace the code in the previous example with:
<code class="language-csharp">BiDictionary<int, string> greek = new BiDictionary<int, string>(); greek.Add(1, "Alpha"); greek.Add(2, "Beta"); greek.Add(5, "Beta"); IEnumerable<int> betaKeys = greek.GetBySecond("Beta"); foreach (int key in betaKeys) { Console.WriteLine(key); // 2, 5 }</code>
This solution effectively provides a way to retrieve all keys associated with a specified value in a multi-valued dictionary.
The above is the detailed content of How to Retrieve Multiple Keys Associated with a Specific Value in a Generic Dictionary?. For more information, please follow other related articles on the PHP Chinese website!