2

我有两个数据表t1t2. 我正在尝试执行 LINQ 左连接、多个等值连接,以获取t1不在t2.

在 SQL 中,我想要完成的是:

select t1.* 
from t1
left join t2
on t1.a=t2.a and
   t1.b=t2.b and
   t1.c=t2.c
where
   t2.a is null

到目前为止,我有以下内容:

public DataTable t1_without_t2(DataTable t1, DataTable t2)
        {
            var query = from t1_row in t1.AsEnumerable()
                        join t2_row in t2.AsEnumerable()
                        on 
                        new { t_a = t1_row["a"], t_b = t1_row["b"], t_c = t1_row["c"]}   
                        equals
                        new { t_a = t2_row["a"], t_b = t2_row["b"], t_c = t2_row["c"]}
                        into leftJoinT1withoutT2
                        from join_row in leftJoinT1withoutT2.DefaultIfEmpty()
                        where t2_row["a"] == null
                        select new
                        {
                            j_a = join_row["a"],
                            j_b = join_row["b"],
                            j_c = join_row["c"],
                        };
            DataTable dt = t1.Clone();
            foreach (var result in query)
            {
                dt.LoadDataRow(
                    new object[]
                    {
                        result.j_a,
                        result.j_b,
                        result.j_c
                    },
                    false);
            }
            return dt;
        }

这是失败的j_a = join_row["a"]这条消息: Column 'a' does not belong to table.

我认为该into leftJoinT1withoutT2行应该将连接的结果放入具有 table 列结构的 var 中t1,从中删除不匹配的条目where t2_row["a"] == null。这不是这里发生的事情吗?我有点困惑。

4

1 回答 1

1

它应该如下所示:

var query = from t1_row in t1.AsEnumerable()
            join t2_row in t2.AsEnumerable()
            on
            new { t_a = t1_row["a"], t_b = t1_row["b"], t_c = t1_row["c"] }
            equals
            new { t_a = t2_row["a"], t_b = t2_row["b"], t_c = t2_row["c"] }
            into leftJoinT1withoutT2
            from join_row in leftJoinT1withoutT2.DefaultIfEmpty()
                                                .Where(r => r == null)
            select new
            {
                j_a = t1_row["a"],
                j_b = t1_row["b"],
                j_c = t1_row["c"],
            };

查看如何:执行左外连接(C# 编程指南)

join_row获取(即null默认TSource值,请参阅Enumerable.DefaultIfEmpty)中没有匹配元素时t2,同时t1_row始终包含连接值。因此,只要您只需要那些行join_rownull我就使用.Where(r => r == null).

于 2012-12-17T07:44:04.680 回答