将键值从NameValueCollection复制到Generic Dictionary

Kob*_*kie 27 .net c# dictionary namevaluecollection

尝试将值从现有的NameValueCollection对象复制到Dictionary.我有以下代码来做到这一点,但似乎Add不接受我的键和值是字符串

IDictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>();
public void copyFromNameValueCollection (NameValueCollection a)
{
    foreach (var k in a.AllKeys)
    { 
        dict.Add(k, a[k]);
    }  
}
Run Code Online (Sandbox Code Playgroud)

注意: NameValueCollection包含字符串键和值,所以我只想在这里提供一种方法,允许将它们复制到通用字典.

kat*_*yte 60

扩展方法加linq:

 public static Dictionary<string, string> ToDictionary(this NameValueCollection nvc) {
    return nvc.AllKeys.ToDictionary(k => k, k => nvc[k]);
 }

 //example
 var dictionary = nvc.ToDictionary();
Run Code Online (Sandbox Code Playgroud)


Lee*_*Lee 33

在这里使用泛型是没有意义的,因为你不能将strings 分配给某些任意泛型类型:

IDictionary<string, string> dict = new Dictionary<string, string>();

public void copyFrom(NameValueCollection a)
{
            foreach (var k in a.AllKeys)
            { 
                dict.Add(k, a[k]);
            }  
}
Run Code Online (Sandbox Code Playgroud)

虽然你应该创建一个方法来创建一个新的字典:

public static IDictionary<string, string> ToDictionary(this NameValueCollection col)
{
    IDictionary<string, string> dict = new Dictionary<string, string>();
    foreach (var k in col.AllKeys)
    { 
        dict.Add(k, col[k]);
    }  
    return dict;
}
Run Code Online (Sandbox Code Playgroud)

您可以使用如下:

NameValueCollection nvc = //
var dictionary = nvc.ToDictionary();
Run Code Online (Sandbox Code Playgroud)

如果您想要将集合中的字符串转换为所需的键/值类型的一般方法,则可以使用类型转换器:

public static Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(this NameValueCollection col)
{
    var dict = new Dictionary<TKey, TValue>();
    var keyConverter = TypeDescriptor.GetConverter(typeof(TKey));
    var valueConverter = TypeDescriptor.GetConverter(typeof(TValue));

    foreach(string name in col)
    {
        TKey key = (TKey)keyConverter.ConvertFromString(name);
        TValue value = (TValue)valueConverter.ConvertFromString(col[name]);
        dict.Add(key, value);
    }

    return dict;
}
Run Code Online (Sandbox Code Playgroud)


小智 15

parameters.AllKeys.ToDictionary(t => t, t => parameters[t]);
Run Code Online (Sandbox Code Playgroud)


aba*_*hev 5

使用 LINQ:

public static IDictionary<string, string> ToDictionary(this NameValueCollection collection)
{
    return collection.Cast<string>().ToDictionary(k => k, v => collection[v]);
}
Run Code Online (Sandbox Code Playgroud)

用法:

IDictionary<string, string> dic = nv.ToDictionary();
Run Code Online (Sandbox Code Playgroud)