如何从c#中的list()打印出对象及其属性?

时间:2013-12-02 21:27:20

标签: c# .net

所以我有一些这样的课程:

class Travel
{
    private int id;
    private string name;
    private List<Traveler> travelers;

    public int ID 
    { get{return id;}
      set{id = value;}
    }

    public string name {
        get { return name;}
        set { name= value; }
    }


    public Travel()
    {
        Travelers = new List<Traveler>();
    }
}

class Traveler
{
    private int passport_number;
    private string name;
    private string last_name;
    private List<Travel> travels;

    public int Passport_number {
      get{return passport_number;}
      set{passport_number= value;}
    }

    public string Name {
        get { return Name;}
        set { Name = value; }
    }

    public string Last_name {
        get { return last_name;}
        set { last_name = value; }
    }

    public List<Travel> Travel
    { get { return travel; }
      set { travel= value;}
    }

    public Traveler()
    {
        Travel= new List<Travel>();
    }
}

然后我用简单的按钮制作某种形式..代码隐藏按钮也很简单:

private void button1_Click(object sender, EventArgs e)
    {
        using (IObjectContainer db = Db4oEmbedded.OpenFile("Travel_by_ship.db"))
        {
            // I'm creating new travel, and new traveler

            Travel t = new Travel();
            t.ID = 1;
            t.Name = "Cruising Nile river";

            Traveler tr = new Traveler();
            tr.Passport= 1;
            tr.Name = "John";
            tr.Last_name= "Locke";

            // Now I'm adding traveler to travel, and vice versa

            tr.Travels.Add(t);
            t.Travelers.Add(tr);

现在我们正在打印旅行者的姓名和姓氏:

MessageBox.Show(tr.Name + " " + tr.Last_name); 

但不会像这样工作,因为它是一个列表:

MessageBox.Show(tr.Name + " " + tr.Travels.Name); 

最后我们来看问题..打印所有旅行者的代码是什么,在这种情况下只有旅行者tr(有他的属性),来自旅行?或者只是旅行者的名字,并在同一个消息框中,带着他将前往的旅行名称?我们如何使用对象及其属性来自List&lt;&gt;?我正在使用C#在面向对象的DB中工作。

3 个答案:

答案 0 :(得分:2)

使用投影:

List<Travelers> travelers = new List<Travelers>();
List<string> travelerNames = travelers.Select(x => x.Name);

List<Travel> travels = new List<Travel>();
List<string> travelNames = travels.Select(x => x.Name);

foreach(string name in travelerNames)
{
    // do something with names
    MessageBox.Show("Name: " + name); 
}

答案 1 :(得分:1)

嗯,您需要遍历旅行列表,因为每次旅行都有自己的名字。所以对于一个特定的旅行者..

var theTraveller = someTraveller you have defined...

foreach(var travel in theTraveller.Travels)
{
    MessageBox.Show(theTraveller.Name + " " + travel.Name);
}

或者相反的情况..

  var theTravel = someTravel you have defined...

    foreach(var traveller in theTravel.Travellers)
    {
        MessageBox.Show(theTravel.Name + " " + traveller.Name);
    }

答案 2 :(得分:0)

乍一看,我会说在你的类中覆盖ToString()方法将是最简单的

class Traveler
{
    ...

    public override string ToString()
    {
      return Name + " " + tr.Travels.Name;
    }
}