Reputation: 35
So I have some classes like this:
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>();
}
}
and:
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>();
}
}
And then I make some kind of form with simple button.. Code behind button is simple too:
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);
So now we are printing name and last name of traveler:
MessageBox.Show(tr.Name + " " + tr.Last_name);
But won't work like this because it's a list:
MessageBox.Show(tr.Name + " " + tr.Travels.Name);
And finally we come to the question.. What would be the code to print all travelers, in this case only traveler tr (with his properties), from travel t? Or just name of traveler and in same message box with name of travel on which he'll be going? How do we use object with their properties from List<>? I'm working in object oriented DB with C#.
Upvotes: 1
Views: 256
Reputation:
At first glance I would say overriding the ToString() method in your classes would be the easiest
class Traveler
{
...
public override string ToString()
{
return Name + " " + tr.Travels.Name;
}
}
Upvotes: 0
Reputation: 3810
Well, you need need to iterate through the list of travels, because each travel has it's own name. So for a given traveler..
var theTraveller = someTraveller you have defined...
foreach(var travel in theTraveller.Travels)
{
MessageBox.Show(theTraveller.Name + " " + travel.Name);
}
Or for the reverse case..
var theTravel = someTravel you have defined...
foreach(var traveller in theTravel.Travellers)
{
MessageBox.Show(theTravel.Name + " " + traveller.Name);
}
Upvotes: 1
Reputation: 12956
Use projection:
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);
}
Upvotes: 2