A NameValueCollection extension method that converts the name-Values to a dictionary. - CSharp System.Collections.Specialized

CSharp examples for System.Collections.Specialized:NameValueCollection

Description

A NameValueCollection extension method that converts the name-Values to a dictionary.

Demo Code


using System.Collections.Specialized;
using System.Collections.Generic;

public class Main{
        /// <summary>A NameValueCollection extension method that converts the nameValues to a dictionary.</summary>
        ////*from www .  ja v a  2 s .co m*/
        /// <param name="nameValues">The nameValues to act on.</param>
        ///
        /// <returns>nameValues as a Dictionary&lt;string,string&gt;</returns>
        public static Dictionary<string, string> ToDictionary(this NameValueCollection nameValues)
        {
            if (nameValues == null) return new Dictionary<string, string>();

            var map = new Dictionary<string, string>();
            foreach (var key in nameValues.AllKeys)
            {
                if (key == null)
                {
                    //occurs when no value is specified, e.g. 'path/to/page?debug'
                    //throw new ArgumentNullException("key", "nameValues: " + nameValues);
                    continue;
                }

                var values = nameValues.GetValues(key);
                if (values != null && values.Length > 0)
                {
                    map[key] = values[0];
                }
            }
            return map;
        }
}

Related Tutorials