Return Linq query results into List object

后端 未结 1 869
遥遥无期
遥遥无期 2021-01-19 07:52

I am trying to return the results of a query into a List object, however the following code, as I normally use, does not work. Still relatively new to Linq, can someone expl

相关标签:
1条回答
  • 2021-01-19 07:55

    Select() and Where() will return IQueryable<T>, not List<T>. You've got to convert it to a List<T> - which actually executes the query (instead of just preparing it).

    You just need to call ToList() at the end of the query. For example:

    // There's no need to declare the variable separately...
    List<AgentProductTraining> productTraining = (from records in db.CourseToProduct
                                                  where records.CourseCode == course.CourseCode
                                                  select records).ToList();
    

    Personally I wouldn't use a query expression though, when all you're doing is a single Where clause:

    // Changed to var just for convenience - the type is still List<AgentProductTraining>
    var productTraining = db.CourseToProduct
                            .Where(records => records.CourseCode == course.CourseCode)
                            .ToList();
    
    0 讨论(0)
提交回复
热议问题