NameValueCollection中VS字典<字符串,字符串> [英] NameValueCollection vs Dictionary<string,string>

查看:516
本文介绍了NameValueCollection中VS字典<字符串,字符串>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
IDictionary的<字符串,字符串>或NameValueCollection中

任何原因,我应该使用字典<字符串,字符串>而不是NameValueCollection中

Any reason I should use Dictionary<string,string> instead of NameValueCollection?

(在C#/。NET框架)

(in C# / .NET Framework)

选项1,使用的NameValueCollection:

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
}



选项2,使用字典<字符串,字符串> ...

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

推荐答案

他们不是相同的语义。在的NameValueCollection 可以有重复键,而词典不能。

They aren't semantically identical. The NameValueCollection can have duplicate keys while the Dictionary cannot.

个人,如果你没有重复键,那么我会坚持使用词典。这是更现代,使用的IEnumerable<> 这使得它易于使用的LINQ 查询打成一片。你甚至可以创建一个词典使用的LINQ ToDictionary()方法。

Personally if you don't have duplicate keys, then I would stick with the Dictionary. It's more modern, uses IEnumerable<> which makes it easy to mingle with Linq queries. You can even create a Dictionary using the Linq ToDictionary() method.

这篇关于NameValueCollection中VS字典&LT;字符串,字符串&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆