Return these records from some parents, of whom their children have a certain property equal to a certain value?

How do I write this request?

var parents = parents.Select(o => o.children.Where(p=>p.property1 == "Something")).ToList();

      

This results in a conversion type error. How can I return some parents based on a condition that is true for their child properties?

+3


source to share


2 answers


This is your request:

parents = parents.Where(p => p.children.Any(c => c.property1 == "Something")).ToList();

      

Enumerable.Where filters a sequence of values ​​based on a predicate, while Enumerable.Select projects each element of the sequence into a new shape.



Enumerable.Any will return true if there is at least 1 child with porperty1 equal to "something"

Like all you have to do is filtering, you just have to useWhere

. You would use Select

if you wanted to create a collection of some type other than the parent itself.

+2


source


Try the code



var parents=    (from p in parents.AsEnumerable()
    where p.children!=null && p.children.property1 =="Something"
    select p).ToList()

      

0


source







All Articles