Home > Net >  C# Lambda Join with an OR condition
C# Lambda Join with an OR condition

Time:10-01

Is it possible to translate this SQL statement into C# lambda syntax?

SELECT *
FROM Table1 t1
INNER JOIN Table2 t2 on t1.Table1_ID = t2.Table1_ID
    OR t1.Some_Other_Column = NULL

For the C# syntax I would do something like this:

context.Table1
    .Join(context.Table2,
        t1 => t1.Table1_ID,
        t2 => t2.Table1_ID,
        (t1, t2) => new { t1, t2 }
    .Select(x => new 
    {
        // start listing out properties here:
        x.t1.first_column,
        x.t1.last_column,
        x.t2.first_column,
        // and so on
    }).ToList();

I'm just not sure how to include the condition: OR t1.Some_Other_Column = NULL into the above statement. Any help would be appreciated.

CodePudding user response:

Not with the Join LINQ operator as it only supports equality for the join expression.

You could do this via a where operation, how a LINQ provider translates this will depend on the provider:

source1.SelectMany(x => source2.Select(y => new { x, y })
       .Where(v => v.x.Prop1 = v.y.Prop1
                || v.x.Prop2 is null)
  • Related