rgb rgb - 15 days ago 5
C# Question

How to convert nested foreach loops with conditions to LINQ

I'd like to ask if it is possible to convert below nested foreach loops to LINQ expression.

public interface IFoo
{
bool IsCorrect(IFoo foo);
void DoSomething(IFoo foo);
}

List<IFoo> listA; //assume that contains items
List<IFoo> listB; //assume that contains items


foreach (var a in listA)
{
foreach (var b in listB)
{
if (b.IsCorrect(a))
{
b.DoSomething(a);
}
}
}

Answer

This should work:

var result =
    from a in listA
    from b in listB
    where b.IsCorrect(a)
    select new {a, b};

foreach (var item in result)
    item.b.DoSomething(item.a);