如何组合两个NameValueCollections?

Use*_*876 4 c# asp.net collections

我有两个NameValueCollections:

NameValueCollection customTag = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("secureAppSettings");
NameValueCollection appSetting = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("appSettings");
Run Code Online (Sandbox Code Playgroud)

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

我如何将它们组合成一个,所以我可以访问两者中的所有元素?

Dav*_* R. 7

要合并集合,请尝试以下操作:

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];
}
Run Code Online (Sandbox Code Playgroud)

使用新allSettings集合访问组合设置.


zzz*_*Bov 5

我尝试了customTag.Add(appSetting);方法,但出现此错误:Collection is read-only.

这意味着该customTag对象是只读的,不能写入。.Add试图修改原始NameValueCollection. System.Configuration包含一个ReadOnlyNameValueCollection扩展NameValueCollection以使其成为只读的,因此尽管转换为 generic NameValueCollection,该对象仍然是只读的。

我如何将它们合二为一,以便我可以访问两者的所有元素?

您所需要的只是将两个集合添加到第三个 writable NameValueCollection

鉴于:

var customTag = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("secureAppSettings");
var appSetting = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("appSettings");
Run Code Online (Sandbox Code Playgroud)

你可以.Add

var collection = new NameValueCollection();
collection.Add(customTag);
collection.Add(appSettings);
Run Code Online (Sandbox Code Playgroud)

但是,NameValueCollection构造函数有一个Add内部调用的简写:

var collection = new NameValueCollection(customTag);
collection.Add(appSettings);
Run Code Online (Sandbox Code Playgroud)

请注意,在这两种情况下, usingAdd都允许向每个键添加多个值。

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