I've got what I think is a working left outer join LINQ query, but I'm having problems with the select because of null values in the right hand side of the join. Here is what I have so far
Dim Os = From e In oExcel
Group Join c In oClassIndexS On c.tClassCode Equals Mid(e.ClassCode, 1, 4)
Into right1 = Group _
From c In right1.DefaultIfEmpty
I want to return all of e
and one column from c
called tClassCode
. I was wondering what the syntax would be. As you can see, I'm using VB.NET.
Update…
Here is the query doing join where I get the error:
_message = "Object reference not set to an instance of an object."
Dim Os = From e In oExcel
Group Join c In oClassIndexS On c.tClassCode Equals Mid(e.ClassCode, 1, 4)
Into right1 = Group _
From c In right1.DefaultIfEmpty
Select e, c.tClassCode
If I remove the c.tClassCode from the select, the query runs without error. So I thought perhaps I needed to do a select new, but I don't think I was doing that correctly either.
Best Answer
EDIT: you need to check
c
for null, specifically thec
after your grouping. See my updates below.You need to do a null check on
tClassCode
c
in your select statement.What type istClassCode
? You should be able to do a null check onthe valuec
and if it's null cast a nullable of the respective type and returned it, otherwise return the actual value.Since I am not sure whattClassCode
is let's assume it's an integer, in which case the cast would be to a nullable integer (Integer?
). With that in mind your select statement, to be added at the end of what you have so far, should resemble:Since
tClassCode
is a string your code would resemble:Depending on what you need to do if
c
is null you could returnString.Empty
instead ofNothing
:Of course you are free to further expand the selection of "e" to project its specific columns by name.
The important thing to realize is that you must check
c
for null before using any of its properties since it might be null depending on the left outer join result for a particular result (row). Back to my earlier example, if you had another field namedPriority
that was an integer you would cast against a nullable: