4est
4est

Reputation: 3168

Replace nested foreach in easy way

I have two nested foreach loop:

foreach (var item in appArray)
{
  if (item.Value == "True")
  {
    foreach (var pair in appSeedData)
    {
      if (item.Key.Contains(pair.Key))
        pair.Value();
    }
  }         
}

It's possbile to do the same code but with LINQ? Or in easiest way?

Upvotes: 3

Views: 3477

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Techincally, you can put a Linq query:

var actions = appArray
  .Where(item => (item.Value == "True")
  .SelectMany(item => appSeedData
    .Where(pair => item.Key.Contains(pair.Key))
    .Select(pair => pair.Value));

and then perform each (Action?) value:

foreach (var action in actions)
  action();

But I doubt if it's more readable; I suggest Linq and foreach combination:

foreach (var item in appArray.Where(x => x.Value == "True")))
  foreach (var pair in appSeedData.Where(p => item.Key.Contains(p.Key)))
    pair.Value();

Upvotes: 7

Tolga Evcimen
Tolga Evcimen

Reputation: 7352

Here is another possible way to go with, but I agree with @Dmitry's answer.

appArray.Where(item => item.Value == "True").ForEach(item => 
    appSeedData.Where(pair => item.Key.Contains(pair.Key)).ForEach(pair => {
        // do work
    }));

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062600

The LINQ way would be:

var values = from item in appArray
             where item.Value == "True"
             from pair in appSeedData
             where item.Key.Contains(pair.Key)
             select pair.Value;

foreach (var value in values) {...}

However, personally I prefer what you had already. It is clear, obvious, etc.

Upvotes: 3

Related Questions