iasksillyquestions
iasksillyquestions

Reputation: 5689

Querying Child Collections in LINQ

I have a collection of objects called Gigs.

Each Gig has an Acts collection.

Using Linq I want to query my collection of gigs to get all gigs where with an act that has an id of 7 for example.

act.id = 7;

So I started writting...

return from gig in qry
       where gig.Acts //not sure how to do this bit
       select gig;

But I'm not sure how you set conditions on the child collection called acts.

Any ideas?

Upvotes: 12

Views: 13699

Answers (2)

Quintin Robinson
Quintin Robinson

Reputation: 82335

Essentially the same as Mike_G, only more verbose syntax and using equality.

var myCollection = from gig in qry
                   where gig.Acts.Any(act => act.ID == 7)
                   select gig;

Just an edit to bring comments to the answer:

Actually query is for an ID on a member (Artist) on the Act object that can be null.

new Query:

var myCollection = from gig in qry
                   where gig.Acts.Any(act => (null != act.Artist) && (act.Artist.ID == 7))
                   select gig;

Upvotes: 14

Mike_G
Mike_G

Reputation: 16502

var x = gigs.Where(g=>g.Acts.Select(a=>a.ID).Contains(7));

these two queries also return the same:

var x = gigs.Where(g=>g.Acts.Count(a=>a.ID == 7) > 0);

var x = gigs.Where(g=>g.Acts.FirstOrDefault(a=>a.ID == 7) != null);

Upvotes: 7

Related Questions