Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach KeyValuePair in NameValueCollection?

Tags:

c#

I have this code:

NameValueCollection nv = HttpUtility.ParseQueryString(queryString);         foreach (KeyValuePair<String,String> pr in nv) {     //process KeyValuePair           } 

This compiles, but when I try to run it I get an InvalidCastException.

Why is this? Why can't I use KeyValuePair to iterate over a NameValueCollection, and what should I use instead?

like image 365
Oliver Avatar asked Dec 05 '11 12:12

Oliver


Video Answer


2 Answers

First of all, NameValueCollection doesn't use KeyValuePair<String,String>. Also, foreach only exposes the key:

NameValueCollection nv = HttpUtility.ParseQueryString(queryString);         foreach (string key in nv) {     var value = nv[key];  } 
like image 79
jgauffin Avatar answered Sep 21 '22 19:09

jgauffin


You can't do that directly, but you can create an extension method like so:

public static IEnumerable<KeyValuePair<string, string>> AsKVP(         this NameValueCollection source ) {     return source.AllKeys.SelectMany(         source.GetValues,         (k, v) => new KeyValuePair<string, string>(k, v)); } 

Then you can do:

NameValueCollection nv = HttpUtility.ParseQueryString(queryString); foreach (KeyValuePair<String,String> pr in nv.AsKVP()) {     //process KeyValuePair           } 

Note: inspired by this. SelectMany is required to handle duplicate keys.

vb.net version:

<Extension> Public Function AsKVP(         source As Specialized.NameValueCollection ) As IEnumerable(Of KeyValuePair(Of String, String))     Dim result = source.AllKeys.SelectMany(         AddressOf source.GetValues,         Function(k, v) New KeyValuePair(Of String, String)(k, v))     Return result End Function 
like image 33
Endy Tjahjono Avatar answered Sep 17 '22 19:09

Endy Tjahjono