Search code examples
asp.netasp.net-mvc-5

Adding items dynamically to the list using foreach loop


I have model InvoiceViewModel which has a property Items which is a list. I want to run foreach on Items property and add it dynamically to the list.

InvoiceViewModel.cs

public class InvoiceViewModel
{
    ...
    public List<ItemsViewModel> Items { get; set; }

}

ItemsViewModel.cs

public class ItemsViewModel
{
    public string Name { get; set; }
    public string UnitPrice { get; set; }
    public string Quantity { get; set; }
    public string TotalAmount { get; set; }
}

I'm using the following code to add Items from InvoiceViewModel dyanmically to the list.

    var Items = InvoiceViewModel.Items;
    var ItemsList = new List<ItemsViewModel>
    {
        foreach (var item in Items)
        {
            new ItemsViewModel { Name = item.Name, UnitPrice = item.UnitPrice, Quantity = item.Quantity, TotalAmount = item.TotalAmount };
        }
    };

The above code is throwing error, } expected


Solution

  • Okay. So, you are looping inside of an object which is syntactically wrong to do. When you initialize a List, the Object initializer expects you to provide a list of the T class. What you should do is:

    var ItemsList = new List<ItemsViewModel>();
    
    foreach (var item in InvoiceViewModel.Items)
    {
        ItemsList.Add(new ItemsViewModel { Name = item.Name, UnitPrice = item.UnitPrice, Quantity = item.Quantity, TotalAmount = item.TotalAmount });
    }
    

    Or you can use LINQ expressions to initialize the object something like this:

    var ItemsList = InvoiceViewModel.Items
                    .Select(item => new ItemsViewModel { Name = item.Name, UnitPrice = item.UnitPrice, Quantity = item.Quantity, TotalAmount = item.TotalAmount })
                    .ToList();