Return Linq query results into List object

后端 未结 1 870
遥遥无期
遥遥无期 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, not List. You've got to convert it to a List - 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 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
    var productTraining = db.CourseToProduct
                            .Where(records => records.CourseCode == course.CourseCode)
                            .ToList();
    

    0 讨论(0)
提交回复
热议问题