LINQ根据项目值获取不同的记录

时间:2012-11-06 17:06:01

标签: linq entity-framework linq-to-sql linq-to-entities

我有以下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 个答案:

答案 0 :(得分:1)

以下是使用GroupBy选择项目的方法。 (你的问题并没有真正指明你想如何使用这些行,所以我只是将它们输出到Debug控制台。)

// 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()
    ));
}