开发者

What casting problem on my query

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
       开发者_如何学Python           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?)


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:

var r = (from p in db.Orders
         select new { p.OrderID, p.OrderDate }).ToList();

Note that the anonymous type will still be enumerable as it's still a generic List<>, and as such it still implements the generic IEnumerable<> interface.

To form a List<Order>, you need to either retrieve complete objects, so select p instead as John Rasch says:

List<Order> r = (from p in db.Orders
                 select p).ToList();

Or select new Orders and build them out of the fields that you're selecting.


 NorthwindDataContext db = new NorthwindDataContext();
        List<Order> r = (from p in db.Orders
                 select p).ToList();

Selecting new {...} creates a new instance of an anonymous type. If you want to select an Order you will have to return Orders from your query. Finally you have to call ToList() because Linq queries return IEnumberable<T>.


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:

using (var context = new NorthwindDataContext())
{
  var allOrders = from p in db.Orders
               select new { p.OrderID, p.OrderDate };

  // Here you can do further processing (to be executed in DB)
  var someOrders = allOrders.Where(ao => ao.OrderDate < DateTime.Today.AddDays(-1));
  Console.WriteLine(someOrders.Count()); // <-- Query will execute here
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜