Jessica
Jessica

Reputation: 3769

How can I do an outer join to more than two tables in LINQ?

I have the following code that I was helped with.

var results =
    from j in table.GetAll()
    join s in refTableStatuses.GetAll() on j.Status equals s.Key2
    join t in refTableTypes.GetAll() on j.Type equals t.Key2
    select new Job
    {
        Key1 = j.Key1,
        Key2 = j.Key2,
        Title = j.Title,
        Status = s.Title, // value from Ref (Status) s
        Type = t.Title    // value from Ref (Type) t
    };

What it does is do a report of jobs and then for each record it looks up the Status and Type using the keys. This code works good however there are some cases where the j.Status and j.Type are null or not set to a matching value in the reference tables.

Is there some way I could do somethink like an outer join? so that even if there is no match of j.Status equals s.Key2 or j.Type equals t.Key2 then I still get to see a result.

Upvotes: 1

Views: 695

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500695

It sounds like you want a left outer join, which is usually done in LINQ like this:

var results =
    from j in table.GetAll()
    join s in refTableStatuses.GetAll() on j.Status equals s.Key2
         into statuses
    from s in statuses.DefaultIfEmpty()
    join t in refTableTypes.GetAll() on j.Type equals t.Key2
         into types
    from t in types
    select new Job
    {
        Key1 = j.Key1,
        Key2 = j.Key2,
        Title = j.Title,
        Status = s == null ? null : s.Title, // value from Ref (Status) s
        Type = t == null ? null : t.Title    // value from Ref (Type) t
    };

Searching for "left outer join LINQ" should get lots of hits for the details about this. This MSDN page is a pretty good starting point.

Upvotes: 1

Related Questions