foreach KeyValuePair in NameValueCollection?
本文关键字:NameValueCollection in KeyValuePair foreach | 更新日期: 2023-09-27 18:16:37
我有这样的代码:
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];
}
您不能直接这样做,但是您可以创建一个扩展方法,像这样:
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
对于将来的参考,您还可以使用以下语法:
foreach(string key in Request.QueryString)
{
var value = Request.QueryString[key];
}
另一个扩展方法,用于学习:
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使用老式的枚举器:
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 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;
}
要将nameValueCollection从QueryString转换为List,可以使用如下扩展:
public static List<KeyValuePair<string, string>> GetParams(this HttpRequest request)
{
var nameValueCollection = HttpUtility.ParseQueryString(request.QueryString.Value);
List<KeyValuePair<string, string>> keyValueCollections = new List<KeyValuePair<string, string>>();
if (!nameValueCollection.IsNullOrEmpty())
{
foreach (var key in nameValueCollection.AllKeys)
{
keyValueCollections.Add(new KeyValuePair<string, string>(key, nameValueCollection[key]));
}
}
return keyValueCollections;
}
如何使用内置的.AsEnumerable()
扩展方法?例子:
NameValueCollection nv = HttpUtility.ParseQueryString(queryString);
foreach (KeyValuePair<String,String> pr in nv.AsEnumerable()) {
//process KeyValuePair
}
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