gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:26:49 25 4
gpt4 key购买 nike

我试图将查询结果返回到 List 对象中,但是我通常使用的以下代码不起作用。对于 Linq 来说还是比较新,有人可以解释一下正确的语法/发生了什么吗?如果我将 productTraining 的数据类型更改为 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> - 它实际执行查询(而不仅仅是准备查询)。

您只需调用 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();

关于linq - 将 Linq 查询结果返回到 List 对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14636280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com