Insert (Add) Linq query result to generic List using C# in ASP.Net MVC

AliYilmaz
 
on Nov 23, 2021 12:38 AM
611 Views

Hello, when the loop below runs, I need to add elements continuously.

I tried to do something like this but it didn't work. How can I solve this problem.

foreach (var item in products)
{
    List<Urunler> list = new List<Urunler>();
 
    list.Add(from p in models
             select new
             {
                 label = p.Name,
                 producturl = Url.RouteUrl("Product", new { SeName = p.SeName }),
                 productpictureurl = p.DefaultPictureModel.ImageUrl
             }; 
 
    result = models.Where(x => x.Id == item.Id).Select(p => new
    { 
        label = p.Name,
        producturl = Url.RouteUrl("Product", new { SeName = p.SeName }),
        productpictureurl = p.DefaultPictureModel.ImageUrl
 
    }).ToList();
}

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Nov 23, 2021 05:28 AM

Based on the item.Id model returning multiple records.

So use AddRange instead of Add method.

List<Urunler> list = new List<Urunler>();
foreach (var item in products)
{
    list.AddRange(models.Where(x => x.Id == item.Id)
             .Select(p => new Urunler
             {
                 label = p.Name,
                 producturl = Url.RouteUrl("Product", new { SeName = p.SeName }),
                 productpictureurl = p.DefaultPictureModel.ImageUrl
             });
}