简体   繁体   中英

Multiple Linq (Extension Method) Joins With Anonymous Types

In C#, I'm attempting to do multiple extension-method joins, in which the second join is with an enumerable of an anonymous type produced by the first join:

List<Contact> filteredContactList = GetFullContacts()
    .Join(GetContactCompanyRoles()
        , ct => ct.IdContact
        , ctCmpRole => ctCmpRole.IdContact
        , (ct, ctCmpRole) => new { Contact = ct, ContactType = ctCmpRole.ContactType })
    .Join(GetContactRoles()
        , ctf => new { ctf.Contact.IdContact, ctf.ContactType }
        , ctRole => new { ctRole.ContactId, ctRole.ContactType }
        , (ctf, ctRole) => new { Contact = ctf.Contact, PrimaryInd = ctRole.IsPrimary})
    .Select(rec => rec.Contact)
    .ToList();

ct and ctf.Contact is of Type Contact.

I am, however, getting the following error when attempting to compile:

The type arguments for method 'System.Linq.Enumerable.Join...' cannot be inferred from the usage. Try specifying the type argument explicitly.

Is there a way to get around this error without having to create an actual class for the anonymous type from the first join? Are there other options that I am not considering?

I notice an apparent typographical error here:

    , ctRole => new { ctRole.IdContact, ctRole.ConatactType }

where perhaps you mean this:

    , ctRole => new { ctRole.IdContact, ctRole.ContactType }

ie use ContactType instead of ConatactType.


After this was resolved, through comment / chat we determined that compiler errors were still occurring because some of the anonymous classes being used to set up the multi-key joins did not have the same member names. In other words, instead of:

   , ctf => new { ctf.Contact.IdContact, ctf.ContactType }
    , ctRole => new { ctRole.ContactId, ctRole.ContactType }

The member names needed to be normalized between the two anyonymous classes:

   , ctf => new { ContactID = ctf.Contact.IdContact, ctf.ContactType }
    , ctRole => new { ContactID = ctRole.ContactId, ctRole.ContactType }

With the help of Vincent Ugenti, it was determined that the compiler could not evaluate the two anonymous types in the join clause arguments for the second join due to a mismatch in property names. When adding

ContactID = 

to both of the anonymous initializers, the code was able to compile.

.Join(GetContactRoles()
    , ctf => new { ContactID = ctf.Contact.IdContact, ctf.ContactType }
    , ctRole => new { ContactID = ctRole.ContactId, ctRole.ContactType }
    , (ctf, ctRole) => new { Contact = ctf.Contact, PrimaryInd = ctRole.IsPrimary})

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