Thursday, March 22, 2012

Linq SelectMany and GroupJoin to do a join

Here's how to do a join between two arrays in a Linq Lambda expression:
var list1 = new int[] {1,2,3,4,5};
var list2 = new int[] {2,3};
var result = list1.SelectMany(l2=>list2, (l1,l2)=>new {l1,l2, sum=l1+l2})
.Where (x=>x.l1==x.l2)
.Select(x=> x); 

The result is this:




And now here is the GroupJoin version which actually does a nice left join:
 
var groupJoinResult = list1
 .GroupJoin(list2, 
  L1=>L1,
  L2=>L2,
  (l1, l2) => new {l1,l2}).Dump();

The result is this:

And finally to do a left join, use DefaultIfEmpty qualifier in inner query of select many, as shown in this stackoverflow q and a.