在NameValueCollection的foreach KeyValuePair?

我有这个代码:

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

这编译,但是当我尝试运行它时,我得到一个InvalidCastException

为什么是这样? 为什么我不能使用KeyValuePair遍历一个NameValueCollection ,我应该使用什么呢?

首先, NameValueCollection不使用KeyValuePair<String,String> 。 另外, foreach只揭露关键:

 NameValueCollection nv = HttpUtility.ParseQueryString(queryString); foreach (string key in nv) { var value = nv[key]; } 

为了将来的参考,你也可以使用这个语法:

 foreach(string key in Request.QueryString) { var value = Request.QueryString[key]; } 

你不能直接这样做,但你可以创build一个扩展方法,如下所示:

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

那你可以这样做:

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

注:受此启发。 SelectMany需要处理重复的密钥。

vb.net版本:

 <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 

另一种扩展方法,用于学习目的:

  public static IEnumerable<KeyValuePair<string, string>> ToIEnumerable(this NameValueCollection nvc) { foreach (string key in nvc.AllKeys) { yield return new KeyValuePair<string, string>(key, nvc[key]); } } 

NameValueCollection使用old-skool枚举器:

  var enu = ConfigurationManager.AppSettings.GetEnumerator(); while(enu.MoveNext()) { string key = (string)enu.Current; string value = ConfigurationManager.AppSettings[key]; } 

我喜欢这个,它的工作原理:

  foreach (string akey in request.Query.Keys.Cast<string>()) writer.WriteLine(akey + " = " + request.Query[akey]); 
 public static void PrintKeysAndValues2( NameValueCollection myCol ) { Console.WriteLine( " [INDEX] KEY VALUE" ); for ( int i = 0; i < myCol.Count; i++ ) Console.WriteLine( " [{0}] {1,-10} {2}", i, myCol.GetKey(i), myCol.Get(i) ); Console.WriteLine(); } 

http://msdn.microsoft.com/en-us/library/system.collections.specialized.namevaluecollection.aspx