Search code examples
c#listasp.net-core-mvc

ASP.NET Core MVC: create an empty List<> of a class model


I am creating an ASP.NET Core MVC app.

I have a class entity like this:

 public class NewModel
 {
        public string? FirstName { get; set; }  
        public string? LastName { get; set; }  
        public string? MiddleInitial { get; set; }
}

I need to create a List<NewModel> of 10 or 20 empty elements.

I wrote this code and it works:

List<NewModel> _new = new();

for (int i = 0; i < 10; i++)
{
     NewModel dependents = new();
     _new.Add(dependents);
}

Is there a neater way to do it?

Thanks.


Solution

  • you can use NBuilder

    first you Install-Package NBuilder of nuget

    then you can use this is code

    var _builder = new Builder(new BuilderSettings { AutoNameProperties = false });
    
    List<NewModel> list = _builder.CreateListOfSize<NewModel>(10).Build().ToList();