将Linq查询结果返回到List对象 [英] Return Linq query results into List object

查看:368
本文介绍了将Linq查询结果返回到List对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将查询结果返回到List对象,但是下面的代码(如我通常使用的那样)不起作用.对于Linq来说还算是新手,有人可以解释正确的语法/发生了什么吗?如果将productTraining的数据类型更改为var ...

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;

推荐答案

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

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).

您只需要在查询结束时调用ToList().例如:

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

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

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

这篇关于将Linq查询结果返回到List对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆