2015-01-20 36 views
2

我有两个NameValueCollections:如何组合两个NameValueCollections?

NameValueCollection customTag = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("secureAppSettings"); 
NameValueCollection appSetting = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("appSettings"); 

我试过customTag.Add(appSetting);方法,但我得到这个错误:Collection is read-only.

我将如何将它们合并为一个,这样我就可以访问所有从两个要素是什么?

+0

如果他们都具有相同的键值,你想要做什么? – 2015-01-20 21:41:35

+0

他们应该覆盖。 – User765876 2015-01-20 21:42:28

+1

哪个应该覆盖? – 2015-01-20 21:45:13

回答

6

要合并的集合,你可以试试下面的:

var secureSettings = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("secureAppSettings"); 
var appSettings = (NameValueCollection)System.Configuration.ConfigurationManager.AppSettings; 

// Initialise a new NameValueCollection with the contents of the secureAppSettings section 
var allSettings = new NameValueCollection(secureSettings); 
// Add the values from the appSettings section 
foreach (string key in appSettings) 
{ 
    // Overwrite any entry already there 
    allSettings[key] = appSettings[key]; 
} 

使用新allSettings收集访问合并设置。

0

I tried customTag.Add(appSetting); method but I get this error: Collection is read-only.

这意味着customTag对象是只读的,无法写入。 .Add尝试修改原始NameValueCollectionSystem.Configuration包含一个ReadOnlyNameValueCollection,其扩展NameValueCollection以使其只能读取,尽管转换为通用NameValueCollection,但该对象仍是只读的。

How would I combine them to one, so i can access all the elements from both?

所有你需要的是将两个集合添加到第三个可写NameValueCollection

考虑:

var customTag = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("secureAppSettings"); 
var appSetting = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("appSettings"); 

你可以.Add两个:

var collection = new NameValueCollection(); 
collection.Add(customTag); 
collection.Add(appSettings); 

然而,NameValueCollection构造有内部调用Add的缩写:

var collection = new NameValueCollection(customTag); 
collection.Add(appSettings); 

请注意,在这两种情况下,使用Add都会允许将多个值添加到每个键。

例如,如果您要合并{foo: "bar"}{foo: "baz"},结果将为{foo: ["bar", "baz"]}(为简洁起见,使用JSON语法)。