AndreyAkinshin
AndreyAkinshin

Reputation: 19071

ICollection to String in a good format in C#

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?

Upvotes: 3

Views: 12968

Answers (5)

Quantum_Joe
Quantum_Joe

Reputation: 191

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}")}]";

Upvotes: 0

Arash Sameni
Arash Sameni

Reputation: 31

You can do it simply like this

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

Upvotes: 1

Jim W
Jim W

Reputation: 4970

You could use string.Join like

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

Upvotes: 8

Matthew Whited
Matthew Whited

Reputation: 22443

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();
}

Upvotes: 1

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68737

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

Upvotes: 11

Related Questions