Search code examples
asp.net-mvclinqviewmodel

How do I remove the foreach from this linq code?


I'm fairly new at MVC and linq and viewmodels in particular. I managed to get a create and index views to work. The "insert" wasn't as hard as the "list".

I have this linq query:

 public ActionResult Index()
        {
            List<BlendElVM> BEVM = new List<BlendElVM>();
            var list = (from Blend in db.blends
                        join BlendEl in db.blendEl on Blend.ID equals BlendEl.ID
                        select new
                        {
                            Blend.ID, Blend.Title, Blend.TransDt, BlendEl.Comment
                        }).ToList();

             foreach (var item in list)
              {
                  BlendElVM o = new BlendElVM(); // ViewModel
                  o.Comment = item.Comment;
                  o.Title = item.Title;
                  o.TransDt = item.TransDt;
                  o.ID = item.ID;
                  BEVM.Add(o);
              }
            return View(BEVM);           
        }

What I'm not sure about is the "foreach" section. When I'm running in debug, the "list" shows up fine, but if I comment out the "foreach" I get an error - ie not expecting the model. What does the foreach do? It has to do with the database, but I don't understand the where it is using the "o" and setting the columns. I thought it would all be in one linq query. Is it possible to combine the two and eliminate the "foreach"?


Solution

  •         var BEVM  = (from blend in db.blends
                        join BlendEl in db.blendEl on Blend.ID equals BlendEl.ID
                        select new BlendELVM
                        {
                            ID = blend.ID, 
                            Title = blend.Title, 
                            TransDT = blend.TransDt, 
                            comment = blendEl.Comment
                        }).ToList();