如何在lambda/Linq表达式中转换这个嵌套foreach

本文关键字:转换 嵌套 foreach 表达式 lambda Linq | 更新日期: 2023-09-27 18:09:40

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

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;
            }
        }
    }
}

如何在lambda/Linq表达式中转换这个嵌套foreach

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));
编辑:

根据@Mephy的评论,

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

因此:

.Any(x => condition(x))

可以缩写为:

.Any(condition)