Retrieving Dictionary Keys by Value in C#
In C#, obtaining a dictionary key by its associated value requires an additional lookup operation beyond standard dictionary functionality. Here's how it can be achieved:
Using the FirstOrDefault() Method:
If values in the dictionary are not guaranteed to be unique, you can use the FirstOrDefault() method of the Enumerable class to find the first matching value:
// Dictionary with string keys and values Dictionary<string, string> types = new Dictionary<string, string>() { { "1", "one" }, { "2", "two" }, { "3", "three" } }; // Get the key associated with the value "one" string myKey = types.FirstOrDefault(x => x.Value == "one").Key;
In this case, myKey will contain the value "1". Note that this approach may not return a key if multiple values in the dictionary have the same value.
Creating an Inverse Dictionary:
Alternatively, if values are unique and are inserted less frequently than read, you can create an inverse dictionary, where values are keys and keys are values:
// Create an inverse dictionary Dictionary<string, string> inverseTypes = new Dictionary<string, string>(); // Populate the inverse dictionary foreach (var kvp in types) { inverseTypes[kvp.Value] = kvp.Key; } // Get the key associated with the value "one" string myKey = inverseTypes["one"];
With this approach, the lookup operation can be performed directly using the inverse dictionary without the need for a separate lookup. Keep in mind that this option involves additional memory overhead due to the creation of the inverse dictionary.
The above is the detailed content of How to Retrieve Dictionary Keys from Values in C#?. For more information, please follow other related articles on the PHP Chinese website!