简体   繁体   English

如何在LINQ中对两个以上的表进行外部联接?

[英]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. 这段代码很好用,但是在某些情况下j.Status和j.Type为空或未在参考表中设置为匹配值。

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. 因此,即使没有匹配的j.Status等于s.Key2或j.Type等于t.Key2,我仍然可以看到结果。

It sounds like you want a left outer join , which is usually done in LINQ like this: 听起来您想要一个左外部联接 ,通常在LINQ中这样完成:

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. 搜索“左外部联接LINQ”应该会获得很多有关此内容的命中。 This MSDN page is a pretty good starting point. 这个MSDN页面是一个很好的起点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM