Skip to main content

Splits a string into a NameValueCollection, where each "namevalue" is separated by the "OuterSeparator". The parameter "NameValueSeparator" sets the split between Name and Value.

        /// <summary>
        /// Splits a string into a NameValueCollection, where each "namevalue"
        /// is separated by the "OuterSeparator". The parameter "NameValueSeparator"
        /// sets the split between Name and Value.
        /// </summary>
        /// <param name="self">String to process</param>
        /// <param name="outerSeparator">Separator for each "NameValue"</param>
        /// <param name="nameValueSeparator">Separator for Name/Value splitting</param>
        /// <returns>NameValueCollection of values.</returns>
        /// <example>
        /// Example:
        ///     string str = "param1=value1;param2=value2";
        ///     NameValueCollection nvOut = str.ToNameValueCollection(';', '=');
        ///
        /// The result is a NameValueCollection where:
        ///     key[0] is "param1" and value[0] is "value1"
        ///     key[1] is "param2" and value[1] is "value2"
        /// </example>
        /// <remarks>http://extensionmethod.net/1686/csharp/string/tonamevaluecollection</remarks>
        public static System.Collections.Specialized.NameValueCollection ToNameValueCollection(
            this string self, char outerSeparator, char nameValueSeparator)
        {
            System.Collections.Specialized.NameValueCollection nvText = null;
            self = self.TrimEnd(outerSeparator);

            if (!string.IsNullOrEmpty(self))
            {
                string[] arrStrings = self.TrimEnd(outerSeparator).Split(outerSeparator);
                for (int i = 0; i < arrStrings.Length; i++)
                {
                    string s = arrStrings[i];
                    int posSep = s.IndexOf(nameValueSeparator);
                    string name = s.Substring(0, posSep);
                    string value = s.Substring(posSep + 1);
                    if (nvText == null)
                    {
                        nvText = new System.Collections.Specialized.NameValueCollection();
                    }
                    nvText.Add(name, value);
                }
            }

            return nvText;
        }