[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 196
  • Last Modified:

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.
  • 2
1 Solution
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!

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now