Home > Enterprise >  Nested foreach refactoring
Nested foreach refactoring

Time:10-25

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?

CodePudding user response:

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.

CodePudding user response:

You can also do this using Linq Query Syntax, but I completely agree with the other comments that your original code is best. But for completeness:

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

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