Reputation: 2230
I'd like to write a linq query which checks an object against a list of objects inside another object.
Here is what I've come up with, which doesn't yield the correct results, because it only defaults to the first one, so objects at both Site 1
and Site 2
only show at Site 1
:
filteredData = data
.where(f => filterInfo.Site.Name.Contains
(f.EtaSites.FirstOrDefault().Site.Name)).ToList()
So, data
is a list, and within each Data
object, there is a list of EtaSites
. Each EtaSite
has a Site
. A Data
object could be in more than one Site
, i.e., there are two EtaSites
objects in the list. My query should pull any Data
object that has the selected Site
in the list. So, for ones at more than one site, we should be able to select Site 1
or Site 2
and return the same Data
object.
Upvotes: 0
Views: 1350
Reputation: 32561
Try this:
filteredData = data
.Where(f => f.EtaSites
.Any(a => filterInfo.Site.Name.Contains(a.Site.Name)))
.ToList();
Anyway, the example above lets you select only the exact matches in your filter. I believe you should consider the one below, if you want that to use a partial matching value in the filterInfo.Site.Name
:
filteredData = data
.Where(f => f.EtaSites
.Any(a => a.Site.Name.Contains(filterInfo.Site.Name)))
.ToList();
Upvotes: 5