我想将我的自定义集合存储为Key,Value也是字符串List的集合.我可以使用KeyvaluePair和hashtable来实现这一点.什么是最合适的匹配,这使我在灵活性方面更具优势?
Joh*_*n K 15
Hashtable是随机访问,内部使用System.Collections.DictionaryEntry作为.NET 1.1的项目; 而.NET 2.0中的强类型System.Collections.Generic.Dictionary使用System.Collections.Generic.KeyValuePair项目也是随机访问.
(注意:在提供示例时,这个答案偏向于.NET 2.0框架 - 这就是为什么它继续使用KeyValuePair而不是DictionaryEntry - 原始问题表明这是要使用的所需类型.)
因为KeyValuePair是一个独立的类,所以您可以手动创建KeyValuePair实例的List或Array,但是将依次访问列表或数组.这与Hashtable或Dictionary形成对比,Hashtable或Dictionary在内部创建自己的元素实例并随机访问.两者都是使用KeyValuePair实例的有效方法.另请参阅有关选择要使用的Collection类的MSDN信息.
总之:使用一小组项目时,顺序访问速度最快,而较大的一组项目则受益于随机访问.
Microsoft的混合解决方案:.NET 1.1中引入的一个有趣的专业集合是System.Collections.Specialized.HybridDictionary,它使用ListDictionary内部表示(顺序访问),而集合很小,然后自动切换到Hashtable内部表示(随机访问)当集合变大时".
C#示例代码
以下示例显示了为不同方案创建的相同键值对实例 - 顺序访问(两个示例),后跟一个随机访问示例.为简单起见,在这些示例中,它们都将使用带有字符串值的int键 - 您可以替换需要使用的数据类型.
这是一个强类型的System.Collections.Generic.List的键值对.
(顺序访问)
// --- Make a list of 3 Key-Value pairs (sequentially accessed) ---
// build it...
List<KeyValuePair<int, string>> listKVP = new List<KeyValuePair<int, string>>();
listKVP.Add(new KeyValuePair<int, string>(1, "one"));
listKVP.Add(new KeyValuePair<int, string>(2, "two"));
// access first element - by position...
Console.Write( "key:" + listKVP[0].Key + "value:" + listKVP[0].Value );
Run Code Online (Sandbox Code Playgroud)
这是一个关键值对的System.Array.
(顺序访问)
// --- Make an array of 3 Key-Value pairs (sequentially accessed) ---
// build it...
KeyValuePair<int, string>[] arrKVP = new KeyValuePair<int, string>[3];
arrKVP[0] = new KeyValuePair<int, string>(1, "one");
arrKVP[1] = new KeyValuePair<int, string>(2, "two");
// access first element - by position...
Console.Write("key:" + arrKVP[0].Key + "value:" + arrKVP[0].Value);
Run Code Online (Sandbox Code Playgroud)
这是一个键值对词典.
(随机访问)
// --- Make a Dictionary (strongly typed) of 3 Key-Value pairs (randomly accessed) ---
// build it ...
Dictionary<int, string> dict = new Dictionary<int, string>();
dict[1] = "one";
dict[2] = "two";
// access first element - by key...
Console.Write("key:1 value:" + dict[1]); // returns a string for key 1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14016 次 |
| 最近记录: |