Tuesday, February 9, 2010

Left Outer Joins in LINQ

To create a left join, you will need to add an into clause after the join statement, add an additional from clause in which you invoke the DefaultIfEmpty method. In my example below, I used the same alias in the second from clause as I used in the join. I did this because the second from clause represents the same data as the join clause. Also, after you put the into clause in the query, the alias from the join is no longer in scope. In the select clause, you will need to handle any nulls that may occur.


var baffMapping =
     from ff in ccFileFormat
     join col in jobColumnMapping on ff.ccFileFormatID equals col.FileFormatID into x
     from col in x.DefaultIfEmpty()
     select new
          PropertyName = ff.PropertyName,
          ColumnName = col == null ? string.Empty : col.ColumnName

No comments:

Post a Comment