user3776749
user3776749

Reputation: 697

How do you write an INNER JOIN with an "OR" in Linq

I am trying to write a Linq query to generate the following SQL

SELECT 
    [t1].[Id], [t2].[value3]
FROM 
    [Table1] AS [t1]
INNER JOIN 
    [Table2] AS [t2] ON [t1].[Id] = [t2].[value1]
                     OR [t1].[Id] = [t2].[value2]

I have seen lots of examples for how to do multiple joins, but none for how to do this type of "one or the other" join.

Upvotes: 0

Views: 41

Answers (2)

Svyatoslav Danyliv
Svyatoslav Danyliv

Reputation: 27282

INNER JOIN

var query = 
    from t1 in context.Table1
    from t2 in context.Table2.Where(t2 => t1.Id == t2.value1 || t1.Id == t2.value2)
    select new 
    { 
        t1.Id,
        t2.value3
    };

LEFT JOIN


var query = 
    from t1 in context.Table1
    from t2 in context.Table2.Where(t2 => t1.Id == t2.value1 || t1.Id == t2.value2)
       .DefaultIfEmpty()
    select new 
    { 
        t1.Id,
        t2.value3
    };

Upvotes: 0

Nutzs
Nutzs

Reputation: 101

var result = from t1 in context.Table1
             from t2 in context.Table2
             where (t1.Id == t2.value1 || t1.Id == t2.value2)
             select new 
                    { 
                        t1.Id,
                        t2.value3
                    };

Upvotes: 1

Related Questions