Java Map equivalent in C#

anonymous-pek picture anonymous-pek · Mar 27, 2009 · Viewed 166.5k times · Source

I'm trying to hold a list of items in a collection with a key of my choice. In Java, I would simply use Map as follows:

class Test {
  Map<Integer,String> entities;

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

Is there an equivalent way of doing this in C#? System.Collections.Generic.Hashset doesn't uses hash and I cannot define a custom type key System.Collections.Hashtable isn't a generic class
System.Collections.Generic.Dictionary doesn't have a get(Key) method

Answer

boj picture boj · Mar 27, 2009

You can index Dictionary, you didn't need 'get'.

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

An efficient way to test/get values is TryGetValue (thanx to Earwicker):

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

With this method you can fast and exception-less get values (if present).

Resources:

Dictionary-Keys

Try Get Value