将列表显示到控制台

时间:2016-08-26 06:46:57

标签: c#

我尝试在控制台中显示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()));

但是发出警告:

  

无法访问的代码

我如何显示列表?

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

试试这个:

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