Return Linq Query Results to List Object
I am trying to return the results of a query to a List object, however the following code, as I usually use, does not work. Still relatively new to Linq, can someone explain the correct syntax / what's going on? This works if I change the data type productTraining
to var
...
List<AgentProductTraining> productTraining = new List<AgentProductTraining>();
productTraining = from records in db.CourseToProduct
where records.CourseCode == course.CourseCode
select records;
source to share
Select()
and Where()
will return IQueryable<T>
, not List<T>
. You have to convert it to List<T>
one that actually executes the request (not just prepares it).
You just need to call ToList()
at the end of your request. For example:
// There 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 would not use a query expression, although when all you do is one sentence Where
:
// Changed to var just for convenience - the type is still List<AgentProductTraining>
var productTraining = db.CourseToProduct
.Where(records => records.CourseCode == course.CourseCode)
.ToList();
source to share