c# - ICollection to String 在 C# 中以良好的格式

标签 c# .net string icollection

我有一个列表:

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/

相关文章:

c# - streamreader 读取 xml 文件,然后 file.move 移动 xml 文件 - c#

c# - 如何在安装过程中创建文件夹?

c# - ASP.NET Core (.NET Core) 和 ASP.NET Core (.NET Framework) 的区别

Javascript - 返回方括号之间的字符串

c# - WPF WebBrowser控件如何禁用IE的快捷键?

c# - 从 XML 文件的最后一个子级中选择值

.net - 如何比较两个字符串列表以找到相同的字符串

.net - ASP.Net Entity Framework ,objectcontext 错误

安卓 : Strange error when returning a simple string from doInBackground

python - python2内部如何处理字符串和unicode?