IT TIP

NameValueCollection의 foreach KeyValuePair?

itqueen 2020. 10. 18. 19:57
반응형

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];

}

직접 할 수는 없지만 다음과 같이 확장 메서드를 만들 수 있습니다.

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은 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]);

Be aware that the key name might appear more than once in the query string and that the comparison is usually case sensitive.
If you want to just get the value of the first matching key and not bothered about case then use this:

        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;
        }

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

참고URL : https://stackoverflow.com/questions/8385677/foreach-keyvaluepair-in-namevaluecollection

반응형