C# 控制台 writeline 打印泛型列表 collection

C# Console writeline print out generics list collection

如果可能的话,我需要用控制台写入线打印出这个通用列表的内容。在此先感谢您的帮助。 这个问题是关于这段特定的代码,我做了很多搜索但没有运气。 代码:

using System;
using System.Collections.Generic;                   
public class Program
{
public class Proto
{
    public string name {get;set;}
    public Object[] data {get;set;} 
}
public  void Main()
{

    metodo().ForEach(item => Console.Write(item + ","));
}

public List<Proto> metodo()
{
    Proto[] myproto = new Proto[5];
    List<Proto> mylist = new List<Proto>();
    for(int i = 0;i<5;i++)
    {
        myproto[i] = new Proto {name = "blahblah",data = new Object[]{"dog","cat",2,3}};
        mylist.Add(myproto[i]);
    }
    int h = mylist.Count;
    Console.WriteLine("{0}\t",h);       
    return mylist;      
}

}## 标题 ##

覆盖 ToString():

public class Proto
{
    public string name {get;set;}
    public Object[] data {get;set;} 
    public override string ToString()
    {
        var dataAsString = data.Aggregate(string.Empty, (current, t) => current + t.ToString());
        return name + dataAsString;  
    }
}

并使用它

metodo().ForEach(item => Console.Write(item.ToString() + ","));

编辑: 如果你想要它作为 JSON。 从 Nuget 为您的项目安装 Json.Net,然后

metodo().ForEach(item => Console.Write(JsonConvert.SerializeObject(item) + Environment.NewLine));