我在微软网站上看了一些关于linq的例子,我看到了一个我需要修改的例子!
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);
}
有一个选择,它会检索CustomerID,OrderID和OrderDate,我想选择CustomerID和一个包含该用户所有订单的System.Collection.Generic.List<int>
!基本上我想按CustomerID对我的订单进行分组,但我注意到linq to entity不允许在select中使用.ToList(object)
。
我想要这样的东西......
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 :(得分:0)
您是否有机会按条款分组?
from orders in context.Orders
group orders by orders.CustomerID into ordersGroup
select new { CustomerID = ordersGroup.Key,
Orders = ordersGroup };
如果不是您想要的,请告诉我。
答案 1 :(得分:0)
尝试:
var orders =
(来自客户的c
从o在c.Orders
其中o.OrderDate&gt; = new DateTime(1998,1,1)
选择新的xpto
{
TheCostumerID = c.CustomerID,
CostumerOrders = o.Select(i =&gt; i.OrderID)
})ToList();
答案 2 :(得分: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()
});