在Linq的Foreach

时间:2009-05-01 03:57:18

标签: linq

我可以用LINQ或代表替换这些foreach吗?

    foreach (List<Shopping.BasketPayment> payList in Basket.basketPayments)
    { 
        foreach (var pay in payList)
        {
            if (pay.paymentMethod == "Money Order" 
            {
                foreach (OrderItem orderItem in order.Items)
                {

2 个答案:

答案 0 :(得分:2)

var qry = from payList in Basket.basketPayments
          from pay in payList
          where pay.paymentMethod == "Money Order"
          from orderItem in order.Items // where did "order" come from?
          ... etc ending in `select` of one or more articles

foreach(var item in qry) {
    // do something with item
}

答案 1 :(得分:0)

var allPayments = Basket.basketPayments.SelectMany(p => p);
var moneyOrders = allPayments.Where(p => p.paymentMethod == "Money Order");

foreach(var payment in moneyOrders)
{
    foreach(OrderItem item in order.Items)
    {

    }
}