159

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

3 Answers 3

194

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

3
  • 14
    Might want to mention TryGetValue as well. Commented Mar 26, 2009 at 23:34
  • Is it O(lg(n)) like Java one? I think not
    – user586399
    Commented Mar 3, 2014 at 11:02
  • 1
    @Desolator Reads are O(1), see the Remarks section of Dictionary<TKey, TValue>'s MSDN page
    – canton7
    Commented Sep 26, 2014 at 10:35
18

Dictionary<,> is the equivalent. While it doesn't have a Get(...) method, it does have an indexed property called Item which you can access in C# directly using index notation:

class Test {
  Dictionary<int,String> entities;

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

If you want to use a custom key type then you should consider implementing IEquatable<> and overriding Equals(object) and GetHashCode() unless the default (reference or struct) equality is sufficient for determining equality of keys. You should also make your key type immutable to prevent weird things happening if a key is mutated after it has been inserted into a dictionary (e.g. because the mutation caused its hash code to change).

11
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;
    }
}
1
  • 6
    This answer is ridiculously old, but you can just return value regardless of the outcome of TryGetValue, since val will be assigned null (i.e. default(string)) if the key doesn't exist.
    – dlev
    Commented Jun 16, 2013 at 7:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.