Equivalente de Java Map en C#


Estoy tratando de mantener una lista de elementos de una colección con una clave de mi elección. En Java, simplemente usaría Map de la siguiente manera:

class Test {
  Map<Integer,String> entities;

  public String getEntity(Integer code) {
    return this.entities.get(code);
  }
}

Hay una forma equivalente de hacer esto en C#? System.Collections.Generic.Hashset no usa hash y no puedo definir una clave de tipo personalizado System.Collections.Hashtable no es una clase genérica
System.Collections.Generic.Dictionary no tiene un método get(Key)

Author: zmbq, 2009-03-27

3 answers

Puedes indexar el diccionario, no necesitabas 'get'.

Dictionary<string,string> example = new Dictionary<string,string>();
...
example.Add("hello","world");
...
Console.Writeline(example["hello"]);

Una manera eficiente de probar/obtener valores es TryGetValue (thanx to Earwicker):

if (otherExample.TryGetValue("key", out value))
{
    otherExample["key"] = value + 1;
}

Con este método puede obtener valores rápidos y sin excepciones (si están presentes).

Recursos:

Diccionario-Claves

Intenta Obtener valor

 170
Author: boj,
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
2014-10-15 13:26:15

El diccionario es el equivalente. Mientras que no tiene un Get(...) método, tiene una propiedad indexada llamada Item a la que se puede acceder en C# directamente usando la notación de índice:

class Test {
  Dictionary<int,String> entities;

  public String getEntity(int code) {
    return this.entities[code];
  }
}

Si desea usar un tipo de clave personalizado, debe considerar implementar IEquatable y sobrescribir Equals(object) y GetHashCode() a menos que la igualdad predeterminada (reference o struct) sea suficiente para determinar la igualdad de claves. También debe hacer que su tipo de clave sea inmutable para evitar ocurren cosas extrañas si una clave es mutada después de haber sido insertada en un diccionario (por ejemplo, porque la mutación causó que su código hash cambiara).

 17
Author: Dave,
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
2009-03-27 00:20:52
class Test
{
    Dictionary<int, string> entities;

    public string GetEntity(int code)
    {
        // java's get method returns null when the key has no mapping
        // so we'll do the same

        string val;
        if (entities.TryGetValue(code, out val))
            return val;
        else
            return null;
    }
}
 10
Author: LukeH,
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
2009-12-01 12:59:15