2012-11-06 33 views
0

我有以下LINQ查詢LINQ獲得基於項目值不重複的記錄

var unallocatedOrders = (from orderLine in context.OrderLineItemDboes 
    where (orderLine.Status == unallocated || orderLine.Status == null) 
     && orderLine.orderline.order.order_status_fk == verified 
    group orderLine 
     by new { orderLine.orderline.ol_id,orderLine.orderline.order.order_id } 
     into g 
    select new { OrderLineId = g.Key.ol_id, Count = g.Count(), OrderId = g.Key.order_id }) 
.ToList(); 

上面的查詢給我結果通過以下方式

Order1 ol1 2 
order1 ol2 3 
order1 ol3 1 
order2 ol1 1 
order2 ol2 2 
order3 ol1 4 
order3 ol2 3 
order3 ol3 2 

我需要通過基於上面的列表迭代訂購ID並需要獲取相應的行數和數量。 我需要將此行ID和數量獲取到字典。 有人可以建議我怎樣才能完成它。

謝謝

回答

1

以下是如何使用GroupBy選擇項目。 (你的問題並沒有真正指定您要使用的線,所以我只是把它們輸出到調試控制檯)。

// group by the OrderId 
foreach (var group in unallocatedOrders.GroupBy(row => row.OrderId)) 
{ 
    Debug.WriteLine(

     // for each line, output "Order x has lines y1, y2, y3..." 
     string.Format("Order {0} has lines {1}", 

      // here the key is the OrderId 
      group.Key, 

      // comma-delimited output 
      string.Join(", ", 

       // select each value in the group, and output its OrderLineId, and quantity 
       group.Select(item => 
        string.Format("{0} (quantity {1})", item.OrderLineId, item.Count) 
       ) 
      ) 
     ) 
    ); 
} 

您可以通過使用ToDictionary得到一個字典查找。

// two-level lookup: 1) OrderId 2) OrderLineId 
var lookup = new Dictionary<int, Dictionary<int, long>>(); 

foreach (var group in unallocatedOrders.GroupBy(row => row.OrderId)) 
{ 
    // add each order to the lookup 
    lookup.Add(group.Key, group.ToDictionary(

     // key selector 
     keySelector: item => item.OrderLineId, 

     // value selector 
     elementSelector: item => item.Count() 
    )); 
} 
+0

感謝您的回覆。我可以將此OrderLineId和Count計爲字典嗎? – Naresh

+0

@Naresh你的意思是像'Dictionary >',其中第一個是訂單查找,第二個讓你按行號查找計數? – McGarnagle

+0

是@dbaseman。這將適合我的要求。 – Naresh