Hooked on LINQ

Hooked on LINQ - Developers' Wiki
for .NET Language Integrated Query

Companion book for this site
LINQ to Objects Using C# 4.0:
Using and Extending LINQ to Objects and Parallel LINQ (PLINQ)
Quick Search

Advanced Search »
I wanted to do an outer join but with more then one column.

Ended up with this and it seems to work, the trick it to have the identical column names in the join.

In this example

We have customers and orders but not the best international indexing so Customer ID not enough for the orders alone, hence the outer join with customer id and country code

    
var query = from c in Customers

join o in Orders on

new {Col1 = c.CustomerID, Col2 = c.CountryCode}

equals

new {Col1 = o.CustomerID, Col2 = o.CountryCode}

into g

from o in g.DefaultIfEmpty()

select new {c.CustomerID, c.CountryCode, OrderId = (o == null ? null : o.OrderId)};

     


Any better ways ? comments ?

cheers Martin

This works because of an optomization in the C# the Anonymous Types which makes types identical if the Anonymous Type declares and initializes the same arguments, in the same order. In this case, Col1 and Col2 is declared in both Anonymous Types during the Join, so the compiler gave them the identical type behind-the-scenes - Now, they share the same type, they can be cleanly compared. Nice solution!

Troy.

If you would like to comment on this page, click on the Discuss button located on the top-right of each page. Feel free to edit any mistakes or omissions you find. If you have an objection or find in-appropriate content then contact the administrator. This website is not affiliated with Microsoft®, all content and opinions are those of the specific author and some advice, solutions and article may contain unintentional errors - please use care. Powered by ScrewTurn Wiki version 2.0.33. Some of the icons created by FamFamFam.