Home > Backend Development > C++ > How to Retrieve Dictionary Keys from Values in C#?

How to Retrieve Dictionary Keys from Values in C#?

Mary-Kate Olsen
Release: 2024-12-27 16:20:15
Original
383 people have browsed it

How to Retrieve Dictionary Keys from Values in C#?

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;
Copy after login

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"];
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template