2010-05-18 124 views
2

我正在看一些关于linq的微软网站的例子,我看到一个我需要修改的例子!SelectMany in Linq to entity

http://msdn.microsoft.com/en-us/vcsharp/aa336758.aspx#SelectManyCompoundfrom3

public void Linq16() 
{ 
List<Customer> customers = GetCustomerList(); 

var orders = 
    from c in customers 
    from o in c.Orders 
    where o.OrderDate >= new DateTime(1998, 1, 1) 
    select new { c.CustomerID, o.OrderID, o.OrderDate }; 

ObjectDumper.Write(orders); 
} 

有选择retrives在客户,订单ID和订购日期的insted的我想选择的客户ID和包含该用户的所有订单System.Collection.Generic.List<int>!基本上我想通过CustomerID对我的订单进行分组,但我注意到linq到实体不允许.ToList(object)在select中。

我想是这样的......

List<Customer> customers = GetCustomerList(); 

var orders = 
    from c in customers 
    from o in c.Orders 
    where o.OrderDate >= new DateTime(1998, 1, 1) 
    select new xpto 
    { 
     TheCostumerID = c.CustomerID, 
     CostumerOrders = o.Select(i=>i.OrderID).ToList(), 
    }; 

...但.ToList()是一个很大的问题,至少对我来说。

我试图找出解决方案,但迄今为止我什么都没做!

请帮帮我。

+0

“ToList”的问题是什么? – 2010-05-18 16:47:47

+0

.ToList()里面的选择在linq to实体似乎不工作! – Brazeta 2010-05-24 10:40:04

回答

0

你有没有机会按子句分组?

from orders in context.Orders 
group orders by orders.CustomerID into ordersGroup 
select new { CustomerID = ordersGroup.Key, 
       Orders = ordersGroup }; 

让我知道,如果它不是你在找什么。

0

尝试:

VAR命令=在客户 (从C选自O在c.Orders 其中o.OrderDate> =新日期时间(1998,1,1) 选择新xpto { TheCostumerID = c.CustomerID,
CostumerOrders = o.Select(i => i.OrderID) })。ToList();

+0

但这个查询的结果是一个int对象列表和一个IEnumerable 里面的对象!我想要的结果是一个列表与一个int和列表里面!你现在看到我的问题了吗? – Brazeta 2010-05-24 10:36:17

0

我已经找到了更多的功能语法更简洁,但我使用的GroupBy的是这样的:

DateTime minDate = new DateTime(1998, 1, 1); 

ordersEntities = entities.Customers.GroupJoin(entities.Orders, // Table to join with 
    customer => customer.Id, order => order.CustomerId, // Properties to match on 
    (customer, orders) => new { 
     Customer = customer, 
     Orders = orders.Where(o => o.Date > minDate) 
    }); 

,然后使用ToList()突然冒出来的LINQ到实体并转化为LINQ到对象(当然,请注意这会如何影响到您数据库的实际SQL查询):

return ordersEntities.ToList() 
    .Select(oe => new { 
     Customer = oe.Customer, 
     Orders = oe.ToList() 
    });