ExtensionMethod.NET Home of 820 C#, Visual Basic, F# and Javascript extension methods

ToString

Concatenates a specified separator String between each element of a specified enumeration, yielding a single concatenated string.

Source

using System;
using System.Collections.Generic;
using System.Text;

namespace ExtensionMethods {

    public static class Extensions {

        /// <summary>
        /// Concatenates a specified separator String between each element of a specified enumeration, yielding a single concatenated string.
        /// </summary>
        /// <typeparam name="T">any object</typeparam>
        /// <param name="list">The enumeration</param>
        /// <param name="separator">A String</param>
        /// <returns>A String consisting of the elements of value interspersed with the separator string.</returns>
        public static string ToString<T>(this IEnumerable<T> list, string separator) {
            StringBuilder sb = new StringBuilder();
            foreach (var obj in list) {
                if (sb.Length > 0) {
                    sb.Append(separator);
                }
                sb.Append(obj);
            }
            return sb.ToString();
        }
    }
}

Example

var i = new int[] { 5, 12, 44, -4 };
Console.WriteLine(i.ToString(":"));

Author: Fons Sonnemans

Submitted on: 31 jan 2008

Language: C#

Type: System.Collections.Generic.IEnumerable<T>

Views: 6357