将Linq查询结果返回到List对象

时间:2013-01-31 22:26:04

标签: linq entity-framework

我试图将查询结果返回到List对象,但是我通常使用的以下代码不起作用。 Linq仍然相对较新,有人可以解释正确的语法/正在发生什么?如果我将productTraining的数据类型更改为var ...

,这将有效
List<AgentProductTraining> productTraining = new List<AgentProductTraining>();  

productTraining = from records in db.CourseToProduct
                  where records.CourseCode == course.CourseCode
                  select records;

1 个答案:

答案 0 :(得分:13)

Select()Where()将返回IQueryable<T>,而非List<T>。你必须将它转换为List<T> - 它实际上执行查询(而不仅仅是准备它)。

您只需在查询结束时调用ToList()即可。例如:

// 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();

我个人不会使用查询表达式,当你所做的只是一个Where子句时:

// Changed to var just for convenience - the type is still List<AgentProductTraining>
var productTraining = db.CourseToProduct
                        .Where(records => records.CourseCode == course.CourseCode)
                        .ToList();