如何在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;
}
}
}
}
答案 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));
修改强>
F(x => g(x))等于F(g)
因此:
.Any(x => condition(x))
可缩短为:
.Any(condition)