2

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?

AndreyAkinshin
  • 18,603
  • 29
  • 96
  • 155
  • it really depends on what you call a good string format. I have writen an extension methods called .ToStrings() that hangs from "IEnumerable" and I have also created a join that allowed you to change the joining pattern. But again it really depends on your format. – Matthew Whited Oct 14 '09 at 16:38
  • @Matthew Whited: I am looking for any format with elements of my ICollection. I am looking for some analog Arrays.toString() from Java – AndreyAkinshin Oct 14 '09 at 16:41
  • You are going to want to wrap something in an extension method. Or to make your own collection base with this support built in. (The advantage of an extension method is you can use it on an IEnumerable already in the system. – Matthew Whited Oct 14 '09 at 16:46

5 Answers5

11

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
  • 67,283
  • 14
  • 105
  • 142
  • You should use `List.ConvertAll` instead of `Select`, since the former is optimized for `List`. – Sam Harwell Oct 14 '09 at 16:51
  • 2
    @280Z28: I am using IEnumerable not List for further extendability. – Yuriy Faktorovich Oct 14 '09 at 16:59
  • If you remove the separator parameter, the name ToString will not work with overload resolution -- object.ToString() have higher precedence. Maybe a different name from "ToString" is preferable. – foson Nov 07 '17 at 15:22
7

You could use string.Join like

"[" + string.Join(", ", list.ConvertAll(i => i.ToString()).ToArray()) +"]";
Jim W
  • 4,890
  • 2
  • 20
  • 26
1

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
  • 22,160
  • 4
  • 52
  • 69
  • This makes a copy of the entire list in process (ToArray()), which misses the advantage of streaming with aggreagate. – Reed Copsey Oct 14 '09 at 16:38
  • 1
    @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 Oct 14 '09 at 16:44
  • @Matthew Whited, you have to tell it to use StringBuilder. – Yuriy Faktorovich Oct 14 '09 at 16:47
  • You should use `List.ConvertAll` instead of `Select`, since the former is optimized for `List`. – Sam Harwell Oct 14 '09 at 16:52
1

You can do it simply like this

var list = new List<int> {1, 2, 3, 4, 5};
Console.WriteLine($"[{string.Join(", ", list)}]");
0

In principle we could aim to use string.join(), but the problem is that this method does not work as expected with type System.Collections.ICollection - instead of the expected string we get something like "System.String[]" - and the same happens if we use LINQ.Aggreate on an ICollection.

Here is what worked for me:

// given myCollection is of type System.Collections.ICollection
var myCollectionAsArray = new ArrayList(myICollection).ToArray();

// method 1 : use string join
var myPrettyString1 = string.Join(", ", myCollectionAsArray);

// method 2 : use LINQ aggregate
var myPrettyString2 = $"[{myCollectionAsArray.Aggregate((i, j) => $"{i}, {j}")}]";
Quantum_Joe
  • 181
  • 5