Search code examples
c#ilist

How can I populate an IList when I create a class?


I have the following class:

public class CityViewModel
{
     public City City { get; set; }
     public IList<CityDetail> CityDetails { get; set; }

     public class CityDetail()
     {
         public CityDetail() {
         Text = new HtmlText();
         ImageFile = String.Empty;
         Correct = false;
         Explanation = new HtmlText();
     }
     public bool   Correct { get; set; }
     public HtmlText Text { get; set; }
     public string ImageFile { get; set; }
     public HtmlText Explanation { get; set; }
}

How can I make it so that when I do something like: var model = new CityViewModel();

That it creates a CityViewModel with ten CityDetail records?


Solution

  • You'll need to add a constructor to your CityViewModel object:

    //Add a constructor
    public CityViewModel()
    {
        //Populate the variable
        CityDetails = Enumerable.Repeat(new CityDetail(), 10).ToList();
    }