Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying Child Collections in LINQ

Tags:

c#

.net

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?

like image 761
iasksillyquestions Avatar asked Feb 06 '09 18:02

iasksillyquestions


2 Answers

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;
like image 107
Quintin Robinson Avatar answered Oct 17 '22 05:10

Quintin Robinson


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);
like image 41
Mike_G Avatar answered Oct 17 '22 04:10

Mike_G