简体   繁体   中英

LINQ lambda with where clause

I'm trying to convert this LINQ statement into a Lambda expression.

totalTickets = (from parent in context.EventParentSponsors
    join sponsor in context.EventSponsors
    on parent.EventSponsorId equals sponsor.EventSponsorId
    where parent.ParentSponsorID == parentId
    select sponsor.InvitationCount).FirstOrDefault();

This is what I have so far:

totalTickets = context.EventParentSponsors
    .Join(context.EventSponsors, 
        parent => parent.EventSponsorId,
        sponsor => sponsor.EventSponsorId, 
        (parent, sponsor) => new { sponsor.InvitationCount })
    .Where(o => o.EventParentSponsors.ParentSponsorId).FirstOrDefault();

but I get this error

AnonymousType#1' does not contain a definition for 'EventParentSponsors'
and no extension method 'EventParentSponsors' accepting a first argument of type     'AnonymousType#1' could be found

What I am missing?

Try this one:

totalTickets = context.EventParentSponsors.Join(context.EventSponsors, 
                                                x=>x.EventSponsorId,
                                                y=>y.EventSponsorId,
                                                (x,y) =>
                                                new 
                                                {
                                                    ID=x.ParentSponsorID , 
                                                    Count = x.InvitationCount 
                                                })
                                          .Where(x=>x.ID==parentId)
                                          .Select(x=>x.Count)
                                          .FirstOrDefault();

If you use LINQPad it will sort of show you what the method looks like in Lambda form:

totalTickets = context.EventParentSponsors
    .Join(context.EventSponsors, 
        parent => parent.EventSponsorId,
        sponsor => sponsor.EventSponsorId, 
        (parent, sponsor) => new { parent = parent, sponsor = sponsor })
    .Where(o => o.parent.EventParentSponsors.ParentSponsorId == parentId)
    .Select(o => o.sponsor.InvitationCount)
    .FirstOrDefault();

The key part you were missing is in your projection. When you use the query syntax, you are basically projecting both the parent and child elements:

(parent, sponsor) => new { parent = parent, sponsor = sponsor })

This is so you have full access to each side for future expressions.

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