Cameron Castillo
Cameron Castillo

Reputation: 2832

LINQ Join: Object reference not set to an instance of an object

I have a list that are generated from Linq to SQL. For simplicity it looks like this:

var myItems = (from my in db.MyTable
                select new
                {
                    UniqueID = my.ID,
                    UserName = my.UserName,
                    CreatedOn = my.CreatedOn
                }).ToList();

This list contains 4 items.

And I have another:

var grid = (from q in AnotherLinqQuery
                select new
                {
                    UniqueID = q.ID,
                    Department = q.Department,
                    Comments = q.Comments
                }).ToList();

This list contains 20 items. All the ID's in myItems appear in grid.

Now I want to join it up with a left join.

var q = from A in grid
        from B in myItems.Where(x => x.UniqueID == grid.UniqueID).DefaultIfEmpty()
        select new 
        {
           UniqueID = A.UniqueID,
           Department = A.Department,
           CreatedOn = B.CreatedOn
        }

When I execute this, I get

Object reference not set to an instance of an object.

I've also tried other joins such as

from A in grid
            from B in myItems.Where(x => x.UniqueID != null && x.UniqueID == grid.UniqueID).DefaultIfEmpty()

Upvotes: 1

Views: 3763

Answers (2)

René Vogt
René Vogt

Reputation: 43876

Since you are doing a left join instead of an inner join, there will be no items from myItems for the 16 elements that are only in grid but not in myItems.

B will be null in that cases (as DefaultIfEmpty() creates a sequence with one null element), so you have to check for null here:

var q = from A in grid
        from B in myItems.Where(x => x.UniqueID == grid.UniqueID).DefaultIfEmpty()
        select new 
        {
           UniqueID = A.UniqueID,
           Department = A.Department,
           CreatedOn = B?.CreatedOn ?? DateTime.MinValue // or whatever default value you like
        }

Upvotes: 2

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 120927

You are not joining correctly. Try this:

var q = from A in grid
        join B in myItems on A.UniqueId equals B.UniqueId into LB
        from B in LB.DefaultIfEmpty()
        select new 
        {
            UniqueID = A.UniqueID,
            Department = A.Department,
            CreatedOn = B.CreatedOn
        };

You may want to refer to the documentation for further info on joining in linq.

Upvotes: 3

Related Questions