我有这段代码:
NameValueCollection nv = HttpUtility.ParseQueryString(queryString);
foreach (KeyValuePair<String,String> pr in nv) {
//process KeyValuePair
}
这是编译,但当我尝试运行它时,我得到一个InvalidCastException
。
这是为什么?为什么我不能使用KeyValuePair
来迭代NameValueCollection
,我应该使用什么呢?
答案 0 :(得分:120)
首先,NameValueCollection
不使用KeyValuePair<String,String>
。此外,foreach
仅公开密钥:
NameValueCollection nv = HttpUtility.ParseQueryString(queryString);
foreach (string key in nv) {
var value = nv[key];
}
答案 1 :(得分:10)
为了将来参考,您还可以使用以下语法:
foreach(string key in Request.QueryString)
{
var value = Request.QueryString[key];
}
答案 2 :(得分:10)
您无法直接执行此操作,但您可以创建类似的扩展方法:
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
}
注意:受this的启发。 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
答案 3 :(得分:5)
另一种扩展方法,用于学习目的:
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]);
}
}
答案 4 :(得分:1)
NameValueCollection使用old-skool枚举器:
var enu = ConfigurationManager.AppSettings.GetEnumerator();
while(enu.MoveNext())
{
string key = (string)enu.Current;
string value = ConfigurationManager.AppSettings[key];
}
答案 5 :(得分:0)
我确实喜欢这个并且有效:
foreach (string akey in request.Query.Keys.Cast<string>())
writer.WriteLine(akey + " = " + request.Query[akey]);
答案 6 :(得分:0)
请注意,键名可能在查询字符串中出现多次,并且比较通常区分大小写。
如果您只想获取第一个匹配键的值而不用担心大小写,请使用以下命令:
public string GetQueryValue(string queryKey)
{
foreach (string key in QueryItems)
{
if(queryKey.Equals(key, StringComparison.OrdinalIgnoreCase))
return QueryItems.GetValues(key).First(); // There might be multiple keys of the same name, but just return the first match
}
return null;
}
答案 7 :(得分:-1)
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