Search code examples
c#.netlinq

Nested foreach refactoring


I have this piece of code:

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

Is it possible to do the same action using one foreach or Linq, or even in a more elegant way?


Solution

  • There are various things you could do, such as:

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

    ... But I think you'll agree it's worse than what you have!

    What you have makes it clear that you're calling notifyCustomer for each combination of notifier and customer, and I don't think there's a way of improving that.