我的查询有什么铸造问题
在 C# vs2008 上工作。我的以下查询显示错误。任何人都可以告诉我问题是什么以及如何解决这个问题。提前致谢。
NorthwindDataContext db = new NorthwindDataContext();
List<Order> r = (from p in db.Orders
select new { p.OrderID, p.OrderDate });
错误信息:
无法隐式转换类型 'System.Linq.IQueryable' 到 '系统.集合.通用.列表'。 存在显式转换(您是 缺少演员?)
Work on C# vs2008.my bellow query show me error.Can any body tell me what's the problem and how to solve this problem.Thanks in advance.
NorthwindDataContext db = new NorthwindDataContext();
List<Order> r = (from p in db.Orders
select new { p.OrderID, p.OrderDate });
Error message:
Cannot implicitly convert type
'System.Linq.IQueryable'
to
'System.Collections.Generic.List'.
An explicit conversion exists (are you
missing a cast?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在尝试将查询表达式分配给
List
对象。那是错误的。您需要调用
ToList()
将查询结果转换为找到的订单列表,并使用匿名类型,因为您仅选择部分数据并创建新的匿名对象:请注意匿名类型仍然是可枚举的,因为它仍然是通用的
List
,因此它仍然实现通用的IEnumerable
接口。要形成
List
,您需要检索完整的对象,因此请按照 John Rasch 的说法选择 p
:或者
选择新的 Order
并根据您选择的字段构建它们。You are trying to assign a query expression to a
List<>
object. That's wrong.You need to call
ToList()
to convert the results of the query to a list of orders found, and use an anonymous type since you're selecting only partial data and creating new anonymous objects:Note that the anonymous type will still be enumerable as it's still a generic
List<>
, and as such it still implements the genericIEnumerable<>
interface.To form a
List<Order>
, you need to either retrieve complete objects, soselect p
instead as John Rasch says:Or
select new Order
s and build them out of the fields that you're selecting.选择。
new {...}
创建匿名类型的新实例。如果您想选择Order
,则必须从查询中返回 Orders。最后,您必须调用 ToList(),因为 Linq 查询返回 IEnumberableSelecting
new {...}
creates a new instance of an anonymous type. If you want to select anOrder
you will have to return Orders from your query. Finally you have to call ToList() because Linq queries returnIEnumberable<T>
.或者根据您稍后要对该查询执行的操作,将其保留为 IQueryable(这将允许您在服务器上进一步过滤和查询,而无需提取所有订单),方法是:
Or depending what you will do with that query later, keep it as a IQueryable (which will allow you further filtering and querying on the server without pulling all orders), by doing: