C#控制台写行打印出泛型列表集合

本文关键字:泛型 列表 集合 打印 控制台 | 更新日期: 2023-09-27 18:24:40

如果可能的话,我需要用控制台写行打印出这个Generic List的内容。提前感谢您的帮助。这个问题是关于这段特定的代码,我做了很多搜索,但没有运气。代码:

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

}##标题##

C#控制台写行打印出泛型列表集合

覆盖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));