【问题标题】:How can I do an outer join to more than two tables in LINQ?如何在 LINQ 中对两个以上的表进行外部连接?
【发布时间】:2012-01-22 20:41:31
【问题描述】:

我有以下代码,我得到了帮助。

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
    };

它所做的是对工作进行报告,然后使用键为每条记录查找状态和类型。此代码运行良好,但在某些情况下 j.Status 和 j.Type 为空或未设置为引用表中的匹配值。

有什么方法可以让我做一些像外部连接一样的思考吗?这样即使没有 j.Status 的匹配等于 s.Key2 或 j.Type 等于 t.Key2 然后我仍然可以看到结果。

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    听起来你想要一个左外连接,这通常在 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
        };
    

    搜索“左外连接 LINQ”应该会获得很多关于此的详细信息。 This MSDN page 是一个很好的起点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-23
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 2012-04-25
      • 2021-05-15
      • 2021-08-24
      相关资源
      最近更新 更多