rgb rgb - 1 year ago 92
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))

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download