ICollection to String in a good format in C#

AndreyAkinshin picture AndreyAkinshin · Oct 14, 2009 · Viewed 8.8k times · Source

I have a List:

List<int> list = new List<int> {1, 2, 3, 4, 5};

If want to get string presentation of my List. But code list.ToString() return "System.Collections.Generic.List'1[System.Int32]"

I am looking for standard method like this:

    string str = list.Aggregate("[",
                               (aggregate, value) =>
                               aggregate.Length == 1 ? 
                               aggregate + value : aggregate + ", " + value,
                               aggregate => aggregate + "]");

and get "[1, 2, 3, 4, 5]"

Is there standard .NET-method for presentation ICollection in good string format?

Answer

Yuriy Faktorovich picture Yuriy Faktorovich · Oct 14, 2009

Not that I'm aware of, but you could do an extension method like the following:

    public static string ToString<T>(this IEnumerable<T> l, string separator)
    {
        return "[" + String.Join(separator, l.Select(i => i.ToString()).ToArray()) + "]";
    }

With the following use:

List<int> list = new List<int> { 1, 2, 3, 4, 5 };
Console.WriteLine(list.ToString(", "));