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?
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With