Returns a comma-separated list of the elements of the passed sequence. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:List

Description

Returns a comma-separated list of the elements of the passed sequence.

Demo Code

//   Copyright (c) Slash Games. All rights reserved.
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Collections;

public class Main{
        /// <summary>
        ///   Returns a comma-separated list of the elements of the passed sequence.
        /// </summary>
        /// <param name="sequence">Sequence to get a comma-separated list of.</param>
        /// <returns>Comma-separated list of the elements of the passed sequence.</returns>
        public static string ToString(IEnumerable sequence)
        {/*  w  w  w  .j  av a 2s .c o m*/
            if (sequence == null)
            {
                return "null";
            }

            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.Append("[");

            foreach (var element in sequence)
            {
                string elementString = element as string;
                if (elementString == null)
                {
                    var elementEnumerable = element as IEnumerable;
                    if (elementEnumerable != null)
                    {
                        elementString = ToString(elementEnumerable);
                    }
                    else
                    {
                        elementString = element.ToString();
                    }
                }

                stringBuilder.AppendFormat("{0}, ", elementString);
            }

            if (stringBuilder.Length > 1)
            {
                stringBuilder[stringBuilder.Length - 2] = ']';
                return stringBuilder.ToString().Substring(0, stringBuilder.Length - 1);
            }

            return "[]";
        }
}

Related Tutorials