如何从appsettings键中获取以特定名称开头的所有值并将其传递给任何数组?

28 c# asp.net web-config asp.net-mvc-4

在我的web.config文件中我有

<appSettings>
    <add key="Service1URL1" value="http://managementService.svc/"/>
    <add key="Service1URL2" value="http://ManagementsettingsService.svc/HostInstances"/>
    ....lots of keys like above
</appSettings>
Run Code Online (Sandbox Code Playgroud)

我想获取Service1URLstring[] repositoryUrls = { ... }c 开头的key 的值并将值传递给我的C#类.我怎样才能做到这一点?

我试过这样的东西,但无法获取值:

foreach (string key in ConfigurationManager.AppSettings)
{
    if (key.StartsWith("Service1URL"))
    {
        string value = ConfigurationManager.AppSettings[key];            
    }

    string[] repositoryUrls = { value };
}
Run Code Online (Sandbox Code Playgroud)

无论是我做错了还是错过了什么.真的很感激任何帮助.

Ann*_* L. 70

我会用一点LINQ:

string[] repositoryUrls = ConfigurationManager.AppSettings.AllKeys
                             .Where(key => key.StartsWith("Service1URL"))
                             .Select(key => ConfigurationManager.AppSettings[key])
                             .ToArray();
Run Code Online (Sandbox Code Playgroud)


TGH*_*TGH 12

您将为每次迭代覆盖数组

List<string> values = new List<string>();
foreach (string key in ConfigurationManager.AppSettings)
        {
            if (key.StartsWith("Service1URL"))
            {
                string value = ConfigurationManager.AppSettings[key];
                values.Add(value);
            }

        }

string[] repositoryUrls = values.ToArray();
Run Code Online (Sandbox Code Playgroud)