linq 嵌套foreach重构

iyr7buue  于 2022-12-06  发布在  其他
关注(0)|答案(2)|浏览(135)

我有这样一段代码:

foreach (var customer in customers)
  {
    foreach (var notifier in this.notifiers)
    {
      notifyCustomer(notifier, customer);
    }
  }

有没有可能使用一个foreach或Linq,或者甚至以更优雅的方式来执行相同的操作?

8i9zcol2

8i9zcol21#

您可以执行各种操作,例如:

foreach ((notifier, customer) in customers.SelectMany(c => this.notifiers.Select(n => (n, c)))
{
    notifyCustomer(notifier, customer);
}

......但我想你会同意这比你现在的情况更糟!
您所拥有的内容清楚地表明,您正在为通知程序和客户的每一个组合调用notifyCustomer,我认为没有改进的方法。

gojuced7

gojuced72#

您也可以使用Linq Query Syntax来实现这一点,但我完全同意其他评论,即您的原始代码是最好的。

var items = 
    from customer in customers 
    from notifier in notifers 
    select (customer, notifier);

foreach (var item in items)
{
    notifyCustomer(item.notifier, item.customer);
}

相关问题