Select object with child list that contains a specific object

Sep 10, 2013 at 7:10 AM
Hello,

I have the following structure:
sites = [
{
id: 1,
name: "sj",
typeList: [ {id:1, name: "all"},  {id:2, name: "dev"}]
}
]

How can I select just the sites that their typeList collection contain one element with name equals to "all"?

Thanks,
Yosi
Oct 13, 2013 at 6:37 AM
Edited Oct 13, 2013 at 6:38 AM
I recently encountered the same problem and I have created a blog post for so I won't forget, please have a look:

http://codingdennis.blogspot.com.au/2013/10/linqjs-where-to-filter-on-sub.html

Cheers,
Dennis
Oct 15, 2013 at 9:52 PM
You must use a sub-query to check the condition in the where-clause. On the sub-query you can use Any (any element is equal to ...) or Single (exactly one element is equal to ...). Any returns true, if one item was found, where the predicate is ok. No more items will be evaluated. The first item who passed the condition is enought. Single will throw an exception, if not exactly one item in the collection passed the check. All items will be evaluated by the condition-function (predicate). If more than one item passed the check, Single will throw an exception immediately. Ok ... back to the question

So i think you are looking for
var filteredSites =   Enumerable.From(sites)
                      .Where(function(siteItem){
                        return Enumerable.From(siteItem.typeList).Any(function(typeListItem){
                          return typeListItem.name == "all";})
                      });
hth