Combines a dictionary of key-value pairs in to a string. - CSharp System

CSharp examples for System:String Convert

Description

Combines a dictionary of key-value pairs in to a string.

Demo Code

//  Copyright ? 2011, Grid Protection Alliance.  All Rights Reserved.
using System.Text.RegularExpressions;
using System.Text;
using System.IO;//from www  .j av a 2  s .  c o m
using System.Globalization;
using System.ComponentModel;
using System.Collections.Generic;
using System;

public class Main{
        /// <summary>
        /// Combines a dictionary of key-value pairs in to a string.
        /// </summary>
        /// <param name="pairs">Dictionary of key-value pairs.</param>
        /// <param name="parameterDelimeter">Character that delimits one key-value pair from another (eg. ';').</param>
        /// <param name="keyValueDelimeter">Character that delimits a key from its value (eg. '=').</param>
        /// <param name="startValueDelimeter">Optional character that marks the start of a value such that value could contain other
        /// <paramref name="parameterDelimeter"/> or <paramref name="keyValueDelimeter"/> characters (e.g., "{").</param>
        /// <param name="endValueDelimeter">Optional character that marks the end of a value such that value could contain other
        /// <paramref name="parameterDelimeter"/> or <paramref name="keyValueDelimeter"/> characters (e.g., "}").</param>
        /// <returns>A string of key-value pairs.</returns>
        /// <remarks>
        /// Values will be escaped within <paramref name="startValueDelimeter"/> and <paramref name="endValueDelimeter"/>
        /// to contain nested key/value pair expressions like the following: <c>normalKVP=-1; nestedKVP={p1=true; p2=0.001}</c>,
        /// when either the <paramref name="parameterDelimeter"/> or <paramref name="keyValueDelimeter"/> are detected in the
        /// value of the key/value pair.
        /// </remarks>
        public static string JoinKeyValuePairs(this Dictionary<string, string> pairs, char parameterDelimeter = ';', char keyValueDelimeter = '=', char startValueDelimeter = '{', char endValueDelimeter = '}')
        {
            // <pex>
            if ((object)pairs == null)
                throw new ArgumentNullException("pairs");
            // </pex>

            char[] delimiters = { parameterDelimeter, keyValueDelimeter };
            StringBuilder result = new StringBuilder();
            string value;

            foreach (string key in pairs.Keys)
            {
                value = pairs[key];

                if (value.IndexOfAny(delimiters) >= 0)
                    value = startValueDelimeter + value + endValueDelimeter;

                result.AppendFormat("{0}{1}{2}{3}", key, keyValueDelimeter, value, parameterDelimeter);
            }

            return result.ToString();
        }
}

Related Tutorials