Chris Anderson

Chris Anderson

  • NA
  • 93
  • 9.3k

How to nest lists in list?

Jan 13 2021 11:06 AM
I'm having problems when creating new list within another list. I'm trying to put the Murid list into the Toys list.  The OOP and lists are quite tricky so any help is much appreciated!

The current code looks like following:
  
  1. abstract class Animal  
  2. {  
  3.     public string Name { getset; }  
  4.     public int Age { getset; }  
  5.     public List Toys { getset; } = new List();  
  6. }  
 
  1. abstract class Toy  
  2. {  
  3.     public int Quality { getset; } = 10;  
  4.     public List Murids { getset; } = new List();  
  5. }  
  1. abstract class Murid : Toy  
  2. {  
  3.     public string Size { getset; }  
  4. }  
  1. class Mouse : Murid  
  2. {  
  3.     public string Something { getset; }  
  4. }  
And this is how I try to create an instance of it:
  1. class Application  
  2. {  
  3.     // Create a new object of type Petowner  
  4.     Petowner petowner = new Petowner();  
  5.   
  6.     public void CreateDummyAnimals()  
  7.     {  
  8.         //Create dummy animals at start  
  9.           
  10.         Petowner.Pets.Add(new Cat  
  11.         {  
  12.             Name = "Kisse",  
  13.             Age = 3,  
  14.             Toys =  
  15.                 new List {  
  16.                     new Bone {Quality = 5},  
  17.                     new Ball { Quality = 7 },  
  18.                     Murids =  
  19.                         new List{  
  20.                             new Mouse{Something = "Hello"},  
  21.                         }  
  22.                     },  
  23.                   
  24.         }  
  25.         });  
  26. }  
 
 

Answers (2)