显示列表到控制台

本文关键字:控制台 列表 显示 | 更新日期: 2023-09-27 18:04:00

我试图在控制台显示List

我的列表代码:

var order = new List<Orders>();
order.Add(new Orders { Date = "" + orders[0].date_created, Name = ""+ orders[0].billing.first_name , Adress = ""+ orders[0].shipping.address_1 + "                     " + orders[0].shipping.address_2 });
order.Add(new Orders { Date = "" + orders[1].date_created, Name = "" + orders[1].billing.first_name, Adress = "" + orders[1].shipping.address_1 + "                     " + orders[1].shipping.address_2 });
order.Add(new Orders { Date = "" + orders[2].date_created, Name = "" + orders[2].billing.first_name, Adress = "" + orders[2].shipping.address_1 + "                     " + orders[2].shipping.address_2 });
order.Add(new Orders { Date = "" + orders[3].date_created, Name = "" + orders[3].billing.first_name, Adress = "" + orders[3].shipping.address_1 + "                     " + orders[3].shipping.address_2 });
order.Add(new Orders { Date = "" + orders[4].date_created, Name = "" + orders[4].billing.first_name, Adress = "" + orders[4].shipping.address_1 + "                     " + orders[4].shipping.address_2 });
return order;

我试着像这样显示它:

Debug.WriteLine(order.ToString()); 

,像这样:

order.ForEach(i => Debug.WriteLine(i.ToString()));

但是给出警告:

访问代码

如何显示列表?

显示列表到控制台

使用Linq,正如在您的第二次尝试接近实际打印,您只需要正确格式化字符串,而不是简单地调用ToString方法:

order.ForEach(o => Debug.WriteLine("Date: " + o.Date + " Adress: " + o.Adress + "Name: " + o.Name));

我知道这不是问题的重点,但我建议您使用ForEach指令来填充列表,因为它将为您的代码增加更多的灵活性。

试试这个:

foreach (var item in order)
{
    Debug.WriteLine(item.ToString());
}

或者如果你有上面提到的多个属性,你可以这样尝试:

foreach (var item in order)
{
    Debug.WriteLine("Date : {0}, Name : {1}, Adress : {2}",item.Date.ToString(), item.Name.ToString(), item.Adress.ToString());
}