Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 212
4est Avatar asked Sep 01 '25 03:09

4est


2 Answers

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();
like image 54
Dmitry Bychenko Avatar answered Sep 02 '25 17:09

Dmitry Bychenko


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.

like image 36
Marc Gravell Avatar answered Sep 02 '25 16:09

Marc Gravell