Efron A.
Efron A.

Reputation: 353

Return those records off some parents from which their children's certain property equals a certain value?

How to write this query? :

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

This comes up with the conversion type error. How can I return some parents based on a condition being true for their children's properties?

Upvotes: 3

Views: 62

Answers (2)

kari kalan
kari kalan

Reputation: 505

Try Code

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

Upvotes: 0

sachin
sachin

Reputation: 2361

This is what your query could be:

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

Enumerable.Where filters a sequence of values based on a predicate whereas Enumerable.Select projects each element of a sequence into a new form.

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

As all you need to do here is the filtering, you just need to use Where. You would have used Select if you wanted to create a collection of some type other than that of the parent itself.

Upvotes: 2

Related Questions