简体   繁体   中英

LINQ Join using dot notation and more than one joining field

I would like to know how I can write an inner join in Linq when joining two tables through more than one field.

For example, say this is the SQL equivalent:

SELECT tableOne.fieldThree

FROM table_One AS tableOne,
     table_Two AS tableTwo,
WHERE
     tableOne.fieldOne == tableTwo.fieldOne AND
     tableOne.fieldTwo == tableTwo.fieldTwo;

I tried this:

tableTwo.Join(tableOne,
              two => new { two.fieldOne, two.fieldTwo },
              one => new { one.fieldOne, one.fieldTwo },
              (two, one) => one.fieldThree)
        .ToList();

But the compiler shows an error that says the method cannot be inferred from usage.

Thanks.

Your approach is good and will work. You only need to fix the compiler error. Probably, the two anonymous types in your query are not the same type. This happens easily if the order of fields is changed, or their types do not exactly match.

This is a C# problem, though. Once you get past that your ORM will support this.

The easiest way i can see is using 'Union' method. Just extract your data from both table by more then one field and then use Union on them. This will join both tables without duplicates.

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