Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy key values from NameValueCollection to Generic Dictionary

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

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 generic dictionary.

like image 439
Kobojunkie Avatar asked May 14 '13 17:05

Kobojunkie


1 Answers

Extension method plus linq:

 public static Dictionary<string, string> ToDictionary(this NameValueCollection nvc) {     return nvc.AllKeys.ToDictionary(k => k, k => nvc[k]);  }   //example  var dictionary = nvc.ToDictionary(); 
like image 98
katbyte Avatar answered Oct 04 '22 02:10

katbyte