shamim
shamim

Reputation: 6778

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

Upvotes: 0

Views: 345

Answers (3)

BoltClock
BoltClock

Reputation: 724452

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.

Upvotes: 7

Mirko
Mirko

Reputation: 4282

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
}

Upvotes: 0

Zebi
Zebi

Reputation: 8882

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

Upvotes: 0

Related Questions