我有一个列表:
List<int> list = new List<int> {1, 2, 3, 4, 5};
如果想得到我的列表的字符串表示。但是代码 list.ToString()
返回 "System.Collections.Generic.List'1[System.Int32]"
我正在寻找这样的标准方法:
string str = list.Aggregate("[",
(aggregate, value) =>
aggregate.Length == 1 ?
aggregate + value : aggregate + ", " + value,
aggregate => aggregate + "]");
并得到 [1, 2, 3, 4, 5]"
是否有标准的 .NET 方法以良好的字符串格式表示 ICollection?
最佳答案
据我所知,您可以执行如下扩展方法:
public static string ToString<T>(this IEnumerable<T> l, string separator)
{
return "[" + String.Join(separator, l.Select(i => i.ToString()).ToArray()) + "]";
}
具有以下用途:
List<int> list = new List<int> { 1, 2, 3, 4, 5 };
Console.WriteLine(list.ToString(", "));
关于c# - ICollection to String 在 C# 中以良好的格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1567466/