C# 将键值从 NameValueCollection 复制到通用字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16549758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Copy key values from NameValueCollection to Generic Dictionary
提问by Kobojunkie
Trying to copy values from an existing NameValueCollection object to a Dictionary. I have the following code below to do that but seems the Add does not accept that my keys and values are as Strings
尝试将现有 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]);
}
}
Note:NameValueCollection contains String keys and values and so I simply want to provide here a method to allow copying of those to a genericdictionary.
注意:NameValueCollection 包含字符串键和值,所以我只想在这里提供一种方法来允许将它们复制到通用字典中。
采纳答案by Lee
It doesn't make sense to use generics here since you can't assign strings to some arbitrary generic type:
在这里使用泛型没有意义,因为您不能将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]);
}
}
although you should probably create a method to create a new dictionary instead:
尽管您可能应该创建一种方法来创建新字典:
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;
}
which you can use like:
你可以像这样使用:
NameValueCollection nvc = //
var dictionary = nvc.ToDictionary();
If you want a general way of converting the strings in the collection into the required key/value types, you can use type converters:
如果您想要将集合中的字符串转换为所需的键/值类型的通用方法,您可以使用类型转换器:
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;
}
回答by Reed Copsey
If you know that your dictionary is always going to contain strings, specify it to contain strings instead of making your class generic:
如果你知道你的字典总是包含字符串,指定它包含字符串而不是让你的类泛型:
IDictionary<string, string> dict = new Dictionary<string, string>();
With this, things will "just work" as written (without the generic method specification).
有了这个,事情将“正常工作”(没有通用方法规范)。
If you need this to be a generic class, and hold generic data, you need some way to convert from stringto TKeyand stringto TValue. You could provide delegates to your copy method to do this:
如果您需要将其作为泛型类并保存泛型数据,则需要某种方式来从stringtoTKey和stringto进行转换TValue。您可以为您的复制方法提供委托来执行此操作:
public void CopyFrom(NameValueCollection a, Func<string, TKey> keyConvert, Func<string, TValue> valueConvert)
{
foreach(var k in a.AllKeys)
{
dict.Add(keyConvert(k), valueConvert(a[k]));
}
}
You would then need to pass a delegate in that would perform the conversion from string to TValueand string to TKey.
然后,您需要传递一个委托来执行从 string toTValue和 string to的转换TKey。
回答by abatishchev
Use LINQ:
使用 LINQ:
public static IDictionary<string, string> ToDictionary(this NameValueCollection collection)
{
return collection.Cast<string>().ToDictionary(k => k, v => collection[v]);
}
Usage:
用法:
IDictionary<string, string> dic = nv.ToDictionary();
回答by katbyte
Extension method plus linq:
扩展方法加linq:
public static Dictionary<string, string> ToDictionary(this NameValueCollection nvc) {
return nvc.AllKeys.ToDictionary(k => k, k => nvc[k]);
}
//example
var dictionary = nvc.ToDictionary();
回答by 1232133d2ffa
Super-Short Version
超短版
var dataNvc = HttpUtility.ParseQueryString(data);
var dataCollection = dataNvc.AllKeys.ToDictionary(o => o, o => dataNvc[o]);
回答by Chobits
parameters.AllKeys.ToDictionary(t => t, t => parameters[t]);
回答by Dmitriy Dokshin
You should not forget about EqualityComparer. But it is not a public property. So, you should use reflection to get it.
你不应该忘记 EqualityComparer。但它不是公共财产。所以,你应该使用反射来获取它。
public static IEqualityComparer GetEqualityComparer(this NameObjectCollectionBase nameObjectCollection)
{
PropertyInfo propertyInfo = typeof(NameObjectCollectionBase).GetProperty("Comparer", BindingFlags.Instance | BindingFlags.NonPublic);
return (IEqualityComparer)propertyInfo.GetValue(nameObjectCollection);
}
public static IEqualityComparer<string> GetEqualityComparer(this NameValueCollection nameValueCollection)
{
return (IEqualityComparer<string>)((NameObjectCollectionBase)nameValueCollection).GetEqualityComparer();
}
public static Dictionary<string, string> ToDictionary(this NameValueCollection nameValueCollection)
{
Dictionary<string, string> dictionary =
nameValueCollection.AllKeys.ToDictionary(x => x, x => nameValueCollection[x], nameValueCollection.GetEqualityComparer());
return dictionary;
}

