NiceYellowEgg
NiceYellowEgg

Reputation: 562

Lambda Composite Join

I'm trying to join the results from one query to filter the results of a second query.

First Query

// get the compound centre number and languageId key
var centreKeys = unitOfWork.CentreTranslationRepository.GetAll()
    .Where(w => w.Language.cuture == searchCulture || w.language_id == 1)
    .GroupBy(g => g.Centre.number)
    .Select(s =>
        new
        {
            CentreNumber = s.Key,
            LanguageId = s.Max(g => g.language_id)
        });

This returns results in the form of:

{ CentreNumber = 1589, LanguageId = 27 }

{ CentreNumber = 261, LanguageId = 1 }  

{ CentreNumber = 1257, LanguageId = 1 }

{ CentreNumber = 925, LanguageId = 1 }  

etc

Second Query

// join onto the translated table
var centres = unitOfWork.CentreTranslationRepository.GetAll()
    .Join(centreKeys,
          centreTranslation => new { centreTranslation.Centre.number, centreTranslation.language_id },
          centreKey => new { centreKey.CentreNumber, centreKey.LanguageId },
          (centreTranslation, centreKey) =>
              new Centre
              {
                  CentreNumber = centreTranslation.Centre.number,
                  name = centreTranslation.Centre.name
                  // etc
              });

Performing the join with a single key works without issue, however as shown above, i'm trying to join using an anonymous composite key.

This is when I get the error:

Error   1   The type arguments for method 'System.Linq.Enumerable.Join<TOuter,TInner,TKey,TResult>(System.Collections.Generic.IEnumerable<TOuter>, System.Collections.Generic.IEnumerable<TInner>, System.Func<TOuter,TKey>, System.Func<TInner,TKey>, System.Func<TOuter,TInner,TResult>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.    C:\Development\SVN\Projects\CentreDirectoryService\CentreDirectoryService\Services\DomainService.cs 32  65  CentreDirectoryService 

What am I doing wrong in the second query?

Upvotes: 0

Views: 2992

Answers (1)

AakashM
AakashM

Reputation: 63378

This:

new { centreTranslation.Centre.number, centreTranslation.language_id }

and this:

new { centreKey.CentreNumber, centreKey.LanguageId }

define objects of different anonymous types. In order for anonymous types to be unified, they need their members to have the same names, the same types, and in the same order. When you don't supply member names, the compiler uses the supplied expressions, so the first makes a type with members number and language_id, and the second makes a type with members CentreNumber and LanguageId.

Try changing the first one to

new {
        CentreNumber = centreTranslation.Centre.number, 
        LanguageId  = centreTranslation.language_id 
    }

(and making the necessary downstream changes).

Upvotes: 6

Related Questions