Converts the specified collection to its string representation. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:ICollection

Description

Converts the specified collection to its string representation.

Demo Code


using System.IO;//w w w . java 2s  .  c om
using System;

public class Main{
        /*******************************/
    /// <summary>
    /// Converts the specified collection to its string representation.
    /// </summary>
    /// <param name="c">The collection to convert to string.</param>
    /// <returns>A string representation of the specified collection.</returns>
    public static String CollectionToString(System.Collections.ICollection c)
    {
        System.Text.StringBuilder s = new System.Text.StringBuilder();

        if (c != null)
        {

            System.Collections.ArrayList l = new System.Collections.ArrayList(c);

            bool isDictionary = (c is System.Collections.BitArray || c is System.Collections.Hashtable || c is System.Collections.IDictionary || c is System.Collections.Specialized.NameValueCollection || (l.Count > 0 && l[0] is System.Collections.DictionaryEntry));
            for (int index = 0; index < l.Count; index++)
            {
                if (l[index] == null)
                    s.Append("null");
                else if (!isDictionary)
                    s.Append(l[index]);
                else
                {
                    isDictionary = true;
                    if (c is System.Collections.Specialized.NameValueCollection)
                        s.Append(((System.Collections.Specialized.NameValueCollection)c).GetKey(index));
                    else
                        s.Append(((System.Collections.DictionaryEntry)l[index]).Key);
                    s.Append("=");
                    if (c is System.Collections.Specialized.NameValueCollection)
                        s.Append(((System.Collections.Specialized.NameValueCollection)c).GetValues(index)[0]);
                    else
                        s.Append(((System.Collections.DictionaryEntry)l[index]).Value);

                }
                if (index < l.Count - 1)
                    s.Append(", ");
            }

            if (isDictionary)
            {
                if (c is System.Collections.ArrayList)
                    isDictionary = false;
            }
            if (isDictionary)
            {
                s.Insert(0, "{");
                s.Append("}");
            }
            else
            {
                s.Insert(0, "[");
                s.Append("]");
            }
        }
        else
            s.Insert(0, "null");
        return s.ToString();
    }
}

Related Tutorials