0

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

0

1 Answer 1

5

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.