我想使用我选择的键保存集合中的项目列表。在Java中,我将简单地使用Map如下:
class Test { Map< Integer,String&实体; public String getEntity(Integer code){ return this.entities.get(code); } }在C#中有同样的方法吗? System.Collections.Generic.Hashset 不使用哈希,我不能定义自定义类型键 System.Collections .Hashtable 不是通用类 System.Collections.Generic.Dictionary 没有 get(Key)方法
解决方案'get'。
字典< string,string> example = new Dictionary< string,string>(); ... example.Add(hello,world); ... Console.Writeline(example [hello]);测试/获取值的有效方法是 TryGetValue (thanx to Earwicker):
if(otherExample.TryGetValue(key,out value)) { otherExample [key] = value + 1;使用这种方法,您可以快速获取值和无异常的值(如果存在) 。资源:
字典键
尝试获取价值
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
解决方案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
更多推荐
Java Map等价于C#
发布评论