2010-05-18 204 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() 
    });