2015-01-20 35 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語法)。