c#打印列表

本文关键字:列表 打印 | 更新日期: 2023-09-27 18:18:34

因此,我正在编写一些涉及列表的类的代码。

我现在有这个

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

namespace excercise_1
{
class Program
{
    static void Main(string[] args)
    {
        Card c1 = new Card("1112211", "Jhon", "Brown", "Wollongong", 2500, 1500);
        Card c2 = new Card("1111457", "Sibel", "Yilmaz", "Figtree", 3251, 3000);
        Card c3 = new Card("3333333", "Suzan", "Yilmaz", "Gywnville", 3000, 5000);
        Card c4 = new Card("4444444", "Bob", "Brown", "Balgownie", 1457, 2000);
        c1.Print();
        c2.Print();
        List<Card> Cards = new List<Card>();
        Cards.Add(c3);
        Cards.Add(c4);
     }

}
class Card
{
    public string id;
    public string first_name;
    public string family_name;
    public string suburb;
    public int postcode;
    public int balance;
    public Card (string id, string first_name, string family_name, string suburb, int postcode, int balance)
    {
        this.id = id;
        this.first_name = first_name;
        this.family_name = family_name;
        this.suburb = suburb;
        this.postcode = postcode;
        this.balance = balance;
    }
    public void Print()
    {
        Console.WriteLine(this.id);
        Console.WriteLine(this.first_name);
        Console.WriteLine(this.family_name);
        Console.WriteLine(this.suburb);
        Console.WriteLine(this.postcode);
        Console.WriteLine(this.balance);
    }
}
}

我需要能够打印我的列表称为卡片。我尝试了各种方法,但都不起作用,我越来越沮丧。如果有人能帮忙,我将不胜感激。

c#打印列表

你可以这样做:

 Cards.ForEach(x=>x.Print());

或者像这样:

foreach (Card card in Cards)
{
    card.Print();
}

1)实现覆盖ToString()像http://msdn.microsoft.com/en-us/library/ms173154 (v = vs.80) . aspx

2)有很多方法可以遍历List,正如上面已经指出的那样

3)试着问谷歌,它会大大缩短你问和得到答案之间的时间,也许你会找到一个或两个指南…像

为什么不使用一个简单的循环呢?

foreach(var card in Cards)
   card.Print();

顺便说一句,你可以考虑为你的类重写ToString而不是Print方法。

使用Foreach打印。

 foreach(var card in Cards)
 {
    card.print();
 }

请:-将所有这些公共变量设为私有。

public string id; // private
public string first_name; // private
public string family_name; // private
public string suburb; // private
public int postcode; // private
public int balance; // private

我不会自己编写打印方法。你可以使用TypeDescriptor。

public static void PrintList(IEnumerable<object> values)
{
    foreach (var obj in values)
    {
        string objString = "";
        foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(obj))
        {
            string name = descriptor.Name;
            object value = descriptor.GetValue(obj);
            objString += string.Format(" {0} = {1} ", name, value);
        }
        Console.WriteLine(objString);
    }
}