How to use Lambda in LINQ select statement

前端 未结 5 2010
孤独总比滥情好
孤独总比滥情好 2020-12-04 08:01

I am trying to select stores using a lambda function and converting the result to a SelectListItem so I can render it. However it is throwing a \"Type of Expression

5条回答
  •  不知归路
    2020-12-04 08:23

    Using Lambda expressions:

    1. If we don't have a specific class to bind the result:

       var stores = context.Stores.Select(x => new { x.id, x.name, x.city }).ToList();
      
    2. If we have a specific class then we need to bind the result with it:

      List stores = context.Stores.Select(x => new SelectListItem { Id = x.id, Name = x.name, City = x.city }).ToList();
      

    Using simple LINQ expressions:

    1. If we don't have a specific class to bind the result:

      var stores = (from a in context.Stores select new { x.id, x.name, x.city }).ToList();
      
    2. If we have a specific class then we need to bind the result with it:

      List stores = (from a in context.Stores select new SelectListItem{ Id = x.id, Name = x.name, City = x.city }).ToList();
      

提交回复
热议问题