0

我有以下 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 和数量添加到字典中。有人可以建议我如何完成它。

谢谢

4

1 回答 1

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()
    ));
}
于 2012-11-06T17:13:53.007 回答