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
This question is related to
c#
java
generics
collections
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;
}
}
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).
Source: Stackoverflow.com