简体   繁体   中英

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?

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;
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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM