NameValueCollection 与 Dictionary
我应该使用 Dictionary
(在 C# / .NET Framework 中)
选项 1,使用 NameValueCollection:
//enter values:
NameValueCollection nvc = new NameValueCollection()
{
{"key1", "value1"},
{"key2", "value2"},
{"key3", "value3"}
};
// retrieve values:
foreach(string key in nvc.AllKeys)
{
string value = nvc[key];
// do something
}
选项 2,使用 Dictionary
//enter values:
Dictionary<string, string> dict = new Dictionary<string, string>()
{
{"key1", "value1"},
{"key2", "value2"},
{"key3", "value3"}
};
// retrieve values:
foreach (KeyValuePair<string, string> kvp in dict)
{
string key = kvp.Key;
string val = kvp.Value;
// do something
}
对于这些用例,使用其中一种与另一种相比是否有任何优势?在性能、内存使用、排序顺序等方面有什么区别吗?
Possible Duplicate:
IDictionary<string, string> or NameValueCollection
Any reason I should use Dictionary<string,string> instead of NameValueCollection?
(in C# / .NET Framework)
Option 1, using NameValueCollection:
//enter values:
NameValueCollection nvc = new NameValueCollection()
{
{"key1", "value1"},
{"key2", "value2"},
{"key3", "value3"}
};
// retrieve values:
foreach(string key in nvc.AllKeys)
{
string value = nvc[key];
// do something
}
Option 2, using Dictionary<string,string>...
//enter values:
Dictionary<string, string> dict = new Dictionary<string, string>()
{
{"key1", "value1"},
{"key2", "value2"},
{"key3", "value3"}
};
// retrieve values:
foreach (KeyValuePair<string, string> kvp in dict)
{
string key = kvp.Key;
string val = kvp.Value;
// do something
}
For these use cases, is there any advantage to use one versus the other? Any difference in performance, memory use, sort order, etc.?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它们在语义上并不相同。
NameValueCollection
可以有重复的键,而Dictionary
则不能。就我个人而言,如果您没有重复的键,那么我会坚持使用
Dictionary
。它更现代,使用IEnumerable<>
,这使得与Linq
查询混合起来很容易。您甚至可以使用Linq
ToDictionary()
方法创建一个Dictionary
。They aren't semantically identical. The
NameValueCollection
can have duplicate keys while theDictionary
cannot.Personally if you don't have duplicate keys, then I would stick with the
Dictionary
. It's more modern, usesIEnumerable<>
which makes it easy to mingle withLinq
queries. You can even create aDictionary
using theLinq
ToDictionary()
method.NameValueCollection
是string
类型,而Dictionary
利用泛型来允许类型变化。请参阅泛型的优点。NameValueCollection
isstring
typed whereasDictionary
leverages generics to allow type variance. See Benefits of Generics.Dictionary
会快得多。NameValueCollection
允许重复键。这在某些情况下可能是不好的,但在其他情况下可能是理想的。字典
不允许重复的键。来自: http://msdn.microsoft.com/en-us/library/ xfhwa508.aspx
Dictionary
will be much faster.NameValueCollection
allows duplicate keys. Which could be bad in certain situations, or desired in other.Dictionary
does not allow duplicate keys.From: http://msdn.microsoft.com/en-us/library/xfhwa508.aspx