Nested foreach loop to LINQ conversion

Viewed 58

I am trying to convert these nested foreach loop to LINQ but output is coming in form of IEnumerable<BPAddress>. Is there any solution?

foreach (var cmt in BPAddresss)
{
   foreach (var t in cmt.BPPhones)
   {
       if (t.PHON_NUMB.Length> 11)
       {
           
       }
   }
}

LINQ Code

var k37 = Target.BPAddresss.Where(x => x.BPPhones.Where(y => y.PHON_NUMB.Length > 11).Count() > 0);
1 Answers

You can use Any:

var query = Target.BPAddresss
    .Where(x => x.BPPhones.Any(y => y.PHON_NUMB.Length > 11));

But note that this will not filter the children by this condition. It just checks if there is at least one phone-number longer than 11 characters.

If you need to filter them, you could use SelectMany:

var longPhoneNumbers = Target.BPAddresss
    .SelectMany(x => x.BPPhones.Where(y => y.PHON_NUMB.Length > 11));
Related