Reputation: 137
it will give me error Unable to cast object of type.
public class CusInfomration
{
public string CustomerName { get; set; }
public string CustomerID { get; set; }
public string OrderDate { get; set; }
public string OrderId { get; set; }
}
var CustomerFromWash = from p in _NorthWindDataContext.Customers
join q in _NorthWindDataContext.Orders
on p.CustomerID equals q.CustomerID
where p.Region == "WA"
select new
{
CustomerName =Convert.ToString(p.CompanyName),
CustomerID = Convert.ToString(p.CustomerID),
OrderId = Convert.ToString(q.OrderID),
OrderDate = Convert.ToString(q.OrderDate),
};
List<cusinfomration> lstCust = (List<cusinfomration>)CustomerFromWash;
Upvotes: 0
Views: 61
Reputation: 124632
That LINQ query returns an IQueryable<T>
. IQueryable<T>
is an interface and List<T>
does not implement it, so there is no way that the underlying, concrete implementation is a List<T>
(it does however implement IEnumerable<T>
, so a cast to that would be valid). Even if it were it would not be a safe cast to make as the .NET folks may want to change out the underlying implementation someday and your cast would be broken. Not a good idea even if it did work initially.
You can call ToList()
on the return value of the LINQ query:
var CustomerFromWash = (from p in _NorthWindDataContext.Customers
join q in _NorthWindDataContext.Orders
on p.CustomerID equals q.CustomerID
where p.Region == "WA"
select new
{
CustomerName =Convert.ToString(p.CompanyName),
CustomerID = Convert.ToString(p.CustomerID),
OrderId = Convert.ToString(q.OrderID),
OrderDate = Convert.ToString(q.OrderDate),
}).ToList();
Even then though you are selecting a collection of anonymous types, not CustInformation
objects. If you want CustInformation
objects to be returned then you will need to:
select new CustInformation
{
// set properties here
}
Upvotes: 4