C# 中的 Java Map 等价物

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/687942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 13:32:41  来源:igfitidea点击:

Java Map equivalent in C#

c#javagenericscollections

提问by

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:

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

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.Hashsetdoesn't uses hash and I cannot define a custom type key System.Collections.Hashtableisn't a generic class
System.Collections.Generic.Dictionarydoesn't have a get(Key)method

在 C# 中是否有等效的方法来执行此操作? System.Collections.Generic.Hashset不使用哈希,我不能定义自定义类型键 System.Collections.Hashtable不是泛型类
System.Collections.Generic.Dictionary没有get(Key)方法

采纳答案by boj

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

你可以索引字典,你不需要'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):

测试/获取值的有效方法是TryGetValue(感谢 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

尝试获取价值

回答by Dave

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:

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

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).

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

回答by LukeH

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;
    }
}