Make sure to check for null in the select of a LINQ to objects query when using a left outer join.
The following example illustrates how to get a method value out of class that is the target of the outer join. The code can be run in LINQPad as a C# program.
class Foo
{
public int FooKey { get; set; }
public string FooVal { get; set; }
}
class Bar
{
public int BarKey { get; set; }
public string BarVal { get; set; }
}
void Main()
{
List<Foo> aListOFoo = new List<Foo> {
new Foo { FooKey = 1, FooVal = "FooVal1" },
new Foo { FooKey = 2, FooVal = "FooVal2" },
new Foo { FooKey = 3, FooVal = "FooVal3" } };
List<Bar> aListOBar = new List<Bar> {
new Bar { BarKey = 1, BarVal = "BarVal1" },
new Bar { BarKey = 2, BarVal = "BarVal2" } };
var q =
from f in aListOFoo
join b in aListOBar on f.FooKey equals b.BarKey into fbJoin
from bLeftJoin in fbJoin.DefaultIfEmpty()
select new {
f.FooVal,
BarVal = bLeftJoin != null ? bLeftJoin.BarVal : null };
q.Dump();
}
The output for the above code in LINQPad:
If the select used bLeftJoin.BarVal without the ternary check for null, then the query would return Object reference not set to an instance of an object.
I'm not a huge fan of LINQ outer join syntax, but LINQ brings me much happiness nonetheless :-)
Next entry: Combine and minify JavaScript (JS) and CSS using AjaxMin
Previous Entry: Use LINQ to page through a collection in memory with LINQ to Objects
Latest entries:
Create absolute URLs using ASP.NET MVC
Comments
My Links
Tags
Follow me
About
Powered by FoxBlog
Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2011, Nathan Fox