我想创建一个具有两个属性的类,例如key
& value
。
我想要一种基于value
给我一个key
的方法。
那么代码是什么?我知道Hashtable
但是如何在C#中实现它?我可以将string
作为密钥吗?
答案 0 :(得分:4)
查看Dictionary<TKey, TValue>
课程:http://msdn.microsoft.com/en-us/library/xfhwa508.aspx
答案 1 :(得分:4)
以下是实现此功能的最佳方法(我使用Int32作为要存储的类型的示例):
Dictionary<String,Int32> dictionary = new Dictionary<String,Int32>
{
// this just loads up the list with
// some dummy data - notice that the
// key is a string and the value is an int
{ "one", 1 },
{ "two", 2 },
{ "three", 3 },
};
现在您可以从Dictionary&lt;,&gt;中获取值。像这样:
dictionary["one"]; // returns 1
dictionary["two"]; // returns 2
答案 2 :(得分:2)
Dictionary<string, T>
可以随心所欲。
答案 3 :(得分:1)
使用Dictionary<string, TypeOfYourVAlue>
答案 4 :(得分:1)
答案 5 :(得分:1)
还有更多实现。有HashSet设计用于集合操作,KeyedCollection是一个易于序列化的哈希表。
答案 6 :(得分:1)
...还有System.Collections.Specialized.NameValueCollection
,大致相当于Dictionary<string,string>
,但允许在同一个键值下存储多个字符串值。引用MSDN文档:
此类可用于标题, 查询字符串和表单数据。