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?
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]; }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With