views:

378

answers:

3

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?

+1  A: 

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();
}
Matthew Whited
This makes a copy of the entire list in process (ToArray()), which misses the advantage of streaming with aggreagate.
Reed Copsey
@Reed: True. but it's also currently 5 elements... I think he has enough memory. Besides does the .Aggregate() use a StringBuilder under the covers? If not the concating strings will probably have bigger performance hit.
Matthew Whited
@Matthew Whited, you have to tell it to use StringBuilder.
Yuriy Faktorovich
You should use `List<int>.ConvertAll` instead of `Select`, since the former is optimized for `List<T>`.
280Z28
Good point. But I was thinking more of IEnumerable<T>.
Matthew Whited
+4  A: 

You could use string.Join like

"[" + string.Join(", ", list.ConvertAll(i => i.ToString()).ToArray()) +"]";
Jim W
This makes a copy of the list in process, though, plus doens't include the [] chars
Reed Copsey
this won't work with a List<int>. You need to change the elements to Strings first.
Matthew Whited
+1: This is the most elegant solution. It's fast and clean. @Reed: The ToString() is much more expensive than the ToArray() so the copy shouldn't be a problem at all.
280Z28
+3  A: 

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(", "));
Yuriy Faktorovich
You should use `List<int>.ConvertAll` instead of `Select`, since the former is optimized for `List<T>`.
280Z28
@280Z28: I am using IEnumerable not List for further extendability.
Yuriy Faktorovich