Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Linq query results into List object

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 explain the correct syntax/what's going on? This will work if I change the data type of productTraining to var...

List<AgentProductTraining> productTraining = new List<AgentProductTraining>();  

productTraining = from records in db.CourseToProduct
                  where records.CourseCode == course.CourseCode
                  select records;
like image 943
NealR Avatar asked Dec 11 '22 18:12

NealR


1 Answers

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();
like image 88
Jon Skeet Avatar answered Feb 02 '23 20:02

Jon Skeet