如何在lambda / Linq表达式中转换此嵌套的foreach

时间:2015-08-24 02:03:24

标签: c# linq lambda

如何在lambda / Linq表达式中转换这个嵌套的foreach以简化代码? 如何在lambda / Linq表达式中转换这个嵌套的foreach以简化代码?

LinkButtonContinue.Enabled = false;
foreach (OrderItem orderItem in order.OrderItemList)
{
    if (orderItem.OrderItemCommitAction.Equals(OrderItemCommitAction.Modify) ||
        orderItem.OrderItemCommitAction.Equals(OrderItemCommitAction.Cancel))
    {
        LinkButtonContinue.Enabled = true;
        break;
    }
    else
    {
        foreach(OrderItem orderItemSLot in orderItem.OrderItemSlotList)
        {
            if (orderItemSLot.OrderItemCommitAction.Equals(OrderItemCommitAction.Modify) ||
            orderItemSLot.OrderItemCommitAction.Equals(OrderItemCommitAction.Cancel))
            {
                LinkButtonContinue.Enabled = true;
                break;
            }
            else 
            {
                LinkButtonContinue.Enabled = false;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

Func<OrderItem, bool> condition = 
    x => x.OrderItemCommitAction == OrderItemCommitAction.Modify ||
         x.OrderItemCommitAction == OrderItemCommitAction.Cancel;

LinkButtonContinue.Enabled =
    order.OrderItemList.Any(x => condition(x)) ||
    order.OrderItemList
         .SelectMany(x => x.OrderItemSlotList)
         .Any(x => condition(x));

修改

根据@Mephycomment

  

F(x => g(x))等于F(g)

因此:

.Any(x => condition(x))

可缩短为:

.Any(condition)