Format IDictionary To String - CSharp System.Collections

CSharp examples for System.Collections:IDictionary

Description

Format IDictionary To String

Demo Code


using System.Collections.Specialized;
using System.Collections;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;/*from  www. java  2  s  .c  o m*/

public class Main{

        public static string FormatToString<TKey, TValue>(IDictionary<TKey, TValue> dic, string format, string separator)
        {
            StringBuilder sb = new StringBuilder();

            foreach (KeyValuePair<TKey,TValue> item in dic)
            {
                sb.AppendFormat(format, item.Key, item.Value);
                sb.Append(separator);
            }

            string s = sb.ToString().TrimEnd(separator.ToCharArray());
            return s;
        }

        public static string FormatToString(IDictionary dic, string format, string separator)
        {
            StringBuilder sb = new StringBuilder();

            foreach (DictionaryEntry item in dic)
            {
                sb.AppendFormat(format, item.Key, item.Value);
                sb.Append(separator);
            }

            string s = sb.ToString().TrimEnd(separator.ToCharArray());
            return s;
        }

        public static string FormatToString(NameValueCollection nvc, string format, string separator)
        {
            StringBuilder sb = new StringBuilder();

            foreach (string key in nvc.Keys)
            {
                sb.AppendFormat(format, key, nvc[key]);
                sb.Append(separator);
            }

            string s = sb.ToString().TrimEnd(separator.ToCharArray());
            return s;
        }

        public static string FormatToString(NameValueCollection nvc)
        {
            return FormatToString(nvc, "{0}={1}", "&");
        }
}

Related Tutorials