tags:

views:

119

answers:

2

How to perform left outer join in C# LINQ to objects without using join-on-equals-into clauses? Is there any way to do that with where clause? Correct problem: For inner join is easy and I have a solution like this

List< JoinPair> innerFinal = (from l in lefts from r in rights where l.Key == r.Key

select new JoinPair { LeftId = l.Id, RightId = r.Id}

but for left outer join I need a solution. Mine is something like this but it's not working

List< JoinPair> leftFinal = (from l in lefts from r in rights
select new JoinPair { LeftId = l.Id, RightId = ((l.Key==r.Key) ? r.Id : 0}

where JoinPair is a class:

public class JoinPair { long leftId; long rightId; }
+2  A: 

Take a look at this example. This query should work:

var leftFinal =
        from l in lefts
        join r in rights on l equals r.Left into lrs
        from lr in lrs.DefaultIfEmpty()
        select new { LeftId = l.Id, RightId = ((l.Key==r.Key) ? r.Id : 0 };
Devart
+1  A: 

As stated on:

101 LINQ Samples - Left outer join

var q =
    from c in categories
    join p in products on c equals p.Category into ps
    from p in ps.DefaultIfEmpty()
    select new { Category = c, ProductName = p == null ? "(No products)" : p.ProductName };
ajay_whiz
Ajay_wiz, please don't just drop a link to an overview page. I have changed your link to link to the correct section on the page, and copied the relevant example.
Jan Jongboom
@Jan okay... thanks!!
ajay_whiz