开发者

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("[",
                               (aggregat开发者_如何学运维e, 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?


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


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


You can do it simply like this

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜