Adding a collection or list to an object

I am creating an object and would like to add a collection of sorts to it.  I have a database table that looks like the following (for example):

Person  Pet  Role
Jim         Cat    5
Jim         Dog   3
Sue        Bird   2
Sue        Fish   3

My object will be associated with a person, like "Jim" in the above.  I will call this the "Person" object.  Is there a way to add a list of the animals, along with their role values into this object, so I can do something like this:

Peson.Name                      //Would return Jim
Person.Animals[1].Name   //Would return Dog
Person.Animals[1].Role    //Would return 3

and also to structure the Person class so it can do loops:

foreach Animal in Person.Animals

Can someone walk me through how to do this?  Thanks.

I am guessing I first need to create the Animal object with the name and role method.  But I am unsure how to add this to the Person class so it can be used like the example above.
Who is Participating?
NicoConnect With a Mentor Commented:
In the Person class:

add a private member:

Private List<Animal> _animals;

Instantiate it in the constructor:

_animals = new List<Animal>();

and add a property:

public List<Animal> Animals {
    get { return _animals; }

then you can do:

Person.Animals[0].Name = "Hamster"  and such.

ehh ofcourse first add a new Animal to the list by:

Animal bird = new Animal();
bird.Name = "Bird";
bird.Role = 21;

and stuff like that.

dentyneAuthor Commented:
Great thanks!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.