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

x
  • 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.
0
dentyne
Asked:
dentyne
  • 2
1 Solution
 
NicoCommented:
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.

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

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

and stuff like that.



0
 
dentyneAuthor Commented:
Great thanks!
0

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