C#中的Java Map等价物

146 c# java generics collections

我正在尝试使用我选择的键来保存集合中的项目列表.在Java中,我只想使用Map如下:

class Test {
  Map<Integer,String> entities;

  public String getEntity(Integer code) {
    return this.entities.get(code);
  }
}
Run Code Online (Sandbox Code Playgroud)

在C#中有相同的方法吗? System.Collections.Generic.Hashset不使用哈希并且我无法定义自定义类型键 System.Collections.Hashtable不是泛型类
System.Collections.Generic.Dictionary没有get(Key)方法

boj*_*boj 177

你可以索引词典,你不需要'得到'.

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

测试/获取值的有效方法是TryGetValue(感谢Earwicker):

if (otherExample.TryGetValue("key", out value))
{
    otherExample["key"] = value + 1;
}
Run Code Online (Sandbox Code Playgroud)

使用此方法,您可以快速且无异常地获取值(如果存在).

资源:

字典密钥

尝试获取价值

  • 可能也想提到TryGetValue. (14认同)

Dav*_*ave 17

字典<,>是等价的.虽然它没有Get(...)方法,但它确实有一个名为Item的索引属性,您可以使用索引表示法直接在C#中访问它:

class Test {
  Dictionary<int,String> entities;

  public String getEntity(int code) {
    return this.entities[code];
  }
}
Run Code Online (Sandbox Code Playgroud)

如果要使用自定义键类型,则应考虑实现IEquatable <>并重写Equals(object)和GetHashCode(),除非默认(引用或结构)相等足以确定键的相等性.如果密钥在插入字典后发生变异(例如,因为变异导致其哈希码发生变化),您还应该使密钥类型不可变,以防止发生奇怪的事情.


Luk*_*keH 10

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这个答案是荒谬的,但你可以只返回值而不管`TryGetValue`的结果,因为如果键不存在,`val`将被赋值为`null`(即`default(string)`). (5认同)