rgb rgb - 3 months ago 20
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))


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)