Question

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?

Was it helpful?

Solution

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(", "));

OTHER TIPS

You could use string.Join like

"[" + string.Join(", ", list.ConvertAll(i => i.ToString()).ToArray()) +"]";

If you have C# 3.0 and LINQ you could do this

var mystring = "[" + string.Join(", ", new List<int> {1, 2, 3, 4, 5}
                     .Select(i=>i.ToString()).ToArray()) + "]";

... here is an example extension method ...

public static string ToStrings<T>(this IEnumerable<T> input)
{
    var sb = new StringBuilder();

    sb.Append("[");
    if (input.Count() > 0)
    {
        sb.Append(input.First());
        foreach (var item in input.Skip(1))
        {
            sb.Append(", ");
            sb.Append(item);
        }
    }
    sb.Append("]");

    return sb.ToString();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top