obtener la clave del diccionario por valor


¿Cómo obtengo una clave de diccionario por valor en C#?

Dictionary<string, string> types = new Dictionary<string, string>()
{
            {"1", "one"},
            {"2", "two"},
            {"3", "three"}
};

Quiero algo como esto:

getByValueKey(string value);

getByValueKey("one") debe ser return "1".

¿Cuál es la mejor manera de hacer esto? ¿Tal vez HashTable, SortedLists?

 287
Author: Cœur, 2010-03-15

7 answers

Los valores no necesariamente tienen que ser únicos, por lo que debe hacer una búsqueda. Puedes hacer algo como esto:

var myKey = types.FirstOrDefault(x => x.Value == "one").Key;

Si los valores son únicos y se insertan con menos frecuencia que se leen, entonces cree un diccionario inverso donde los valores son claves y las claves son valores.

 504
Author: Kimi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-25 15:45:20

Usted podría hacer eso:

  1. Repasando todos los KeyValuePair<TKey, TValue> ' s en el diccionario (lo que será un éxito de rendimiento considerable si tiene un número de entradas en el diccionario)
  2. Utilice dos diccionarios, uno para la asignación de valor a clave y otro para la asignación de clave a valor (que ocuparía el doble de espacio en memoria).

Use el Método 1 si el rendimiento no es una consideración, use el Método 2 si la memoria no es una consideración.

Además, todas las claves deben ser únicas, pero no se requiere que los valores sean únicos. Puede tener más de una clave con el valor especificado.

¿Hay alguna razón por la que no pueda revertir la relación clave-valor?

 23
Author: Zach Johnson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-14 22:35:21

Estaba en una situación en la que el enlace Linq no estaba disponible y tuve que expandir lambda explícitamente. Resultó en una función simple:

public static string KeyByValue(Dictionary<string, string> dict, string val)
{
    string key = null;
    foreach (KeyValuePair<string, string> pair in dict)
    {
        if (pair.Value == val)
        { 
            key = pair.Key; 
            break; 
        }
    }
    return key;
}

Llámalo como sigue:

public static void Main()
{
    Dictionary<string, string> dict = new Dictionary<string, string>()
    {
        {"1", "one"},
        {"2", "two"},
        {"3", "three"}
    };

    string key = KeyByValue(dict, "two");       
    Console.WriteLine("Key: " + key);
}

Funciona en.NET 2.0 y en otros entornos limitados.

 2
Author: Boris Zinchenko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-23 11:01:29

Tal vez algo como esto:

foreach (var keyvaluepair in dict)
{
    if(Object.ReferenceEquals(keyvaluepair.Value, searchedObject))
    {
        //dict.Remove(keyvaluepair.Key);
        break;
    }
}
 -1
Author: Shimon Doodkin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-12 10:58:04

El Código inferior solo funciona si contiene Datos de Valor Únicos

public string getKey(string Value)
{
    if (dictionary.ContainsValue(Value))
    {
        var ListValueData=new List<string>();
        var ListKeyData = new List<string>();

        var Values = dictionary.Values;
        var Keys = dictionary.Keys;

        foreach (var item in Values)
        {
            ListValueData.Add(item);
        }

        var ValueIndex = ListValueData.IndexOf(Value);
        foreach (var item in Keys)
        {
            ListKeyData.Add(item);
        }

        return  ListKeyData[ValueIndex];

    }
    return string.Empty;
}
 -2
Author: Pradeep Kumar Das,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-12 10:59:14
types.Values.ToList().IndexOf("one");

Valores.ToList () convierte los valores del diccionario en una Lista de objetos. indexOf ("one") busca en su nueva Lista buscando" one " y devuelve el Índice que coincidiría con el índice del par Clave/Valor en el diccionario.

Este método no se preocupa por las claves del diccionario, simplemente devuelve el índice del valor que está buscando.

Tenga en cuenta que puede haber más de un valor "one" en su diccionario. Y esa es la razón por la que no hay "get key" método.

 -3
Author: EricM,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-11 23:09:34

Tengo una manera muy sencilla de hacer esto. Funcionó perfecto para mí.

Dictionary<string, string> types = new Dictionary<string, string>();

types.Add("1", "one");
types.Add("2", "two");
types.Add("3", "three");

Console.WriteLine("Please type a key to show its value: ");
string rLine = Console.ReadLine();

if(types.ContainsKey(rLine))
{
    string value_For_Key = types[rLine];
    Console.WriteLine("Value for " + rLine + " is" + value_For_Key);
}
 -11
Author: Dushyant Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-28 01:52:05