C# C语言中的Java映射等价物#

C# C语言中的Java映射等价物#,c#,java,generics,collections,C#,Java,Generics,Collections,我试图用我选择的键保存集合中的项目列表。在Java中,我将简单地使用Map,如下所示: class Test { Map<Integer,String> entities; public String getEntity(Integer code) { return this.entities.get(code); } } 类测试{ 地图实体; 公共字符串getEntity(整数代码){ 返回此.entities.get(代码); } } 在C#中是否有类似

我试图用我选择的键保存集合中的项目列表。在Java中,我将简单地使用Map,如下所示:

class Test {
  Map<Integer,String> entities;

  public String getEntity(Integer code) {
    return this.entities.get(code);
  }
}
类测试{
地图实体;
公共字符串getEntity(整数代码){
返回此.entities.get(代码);
}
}
在C#中是否有类似的方法?
System.Collections.Generic.Hashset
不使用哈希,我无法定义自定义类型键
System.Collections.Hashtable
不是泛型类

System.Collections.Generic.Dictionary
没有
get(Key)
方法

您可以索引字典,不需要“get”

Dictionary<string,string> example = new Dictionary<string,string>();
...
example.Add("hello","world");
...
Console.Writeline(example["hello"]);
使用此方法,您可以快速且无异常地获取值(如果存在)

资源:

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

class Test {
  Dictionary<int,String> entities;

  public String getEntity(int code) {
    return this.entities[code];
  }
}
类测试{
字典实体;
公共字符串getEntity(int代码){
返回此.entities[代码];
}
}

如果您想使用自定义键类型,则应该考虑实现IEQualEt和重写等号(object)和GethAsHeDe(),除非默认(引用或结构)相等足以确定键的相等性。您还应该使密钥类型不可变,以防止在将密钥插入字典后发生变异(例如,因为变异导致其哈希代码发生更改)时发生奇怪的事情。

类测试
{
字典实体;
公共字符串GetEntity(int代码)
{
//当键没有映射时,java的get方法返回null
//所以我们也会这么做
字符串val;
if(entities.TryGetValue(代码,输出值))
返回val;
其他的
返回null;
}
}

可能也想提到TryGetValue。它是不是像Java one一样
O(lg(n))
?我想not@Desolator读数为O(1),请参见字典MSDN页面的备注部分。这个答案太旧了,但不管
TryGetValue
的结果如何,您都可以返回值,因为如果键不存在,
val
将被分配
null
(即
默认值(字符串)
)。
class Test {
  Dictionary<int,String> entities;

  public String getEntity(int code) {
    return this.entities[code];
  }
}
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;
    }
}