Linq-左外连接两个数据表 [英] Linq - Left Outer Join Two Datatables

查看:75
本文介绍了Linq-左外连接两个数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有人可以帮助我.我是LINQ的新手,仍在尝试了解它们如何组合在一起.

我在SQL中有一个简单的左联接查询,返回表1上表2中不存在的所有事务.两个表的结构都相同.

I am wondering if anyone can help me. I am new to LINQ and still trying to understand how it fits together.

I have a simple left join query in SQL, returning all transactions that are on table 1 that do not exist in table 2. Both tables are identical in structure.

SELECT Table1.*
FROM Table1 LEFT JOIN Table2 ON Table1.DealReference = Table2.DealReference
WHERE (((Table2.DealReference) Is Null))



有人可以指导我,如何在LinQ中实现相同目标.

我正在使用以下数据表:



Can someone please guide me, how to achieve the same in LinQ.

I am using the following DataTables:

Dim currentDataTable
Dim previousDataTable



我希望将结果输出回到数据表中.
基本上,仅存在于表1中但不存在于表2中的交易.

谢谢

BM



I am looking to have the results output back into a datatable.
Basically only trades that exist in table 1 but do not exist in table 2.

Thanks

BM

推荐答案

我的VB语法有点生锈,但是在这里

首先,有一种更好的方法来放置您的SQL:
Bit rusty on my VB syntax but here goes

first off, there is a better way to put your SQL:
SELECT *
FROM Table1 t1
Where not exists (
  select * from Table2 t2 
  Where t1.DealReference = t2.DealReference
)


这样可以最小化扫描的内容,因此效率更高.请记住,您可以创建反映此逻辑的linq查询


This minimises the content scanned so is much more efficient. That in mind you can create linq queries that reflect this logic

public function ByExtensions() '' .Net4.0 only

  var result = db.table1.Where(t1=>!db.table2.Any(t2=>t2.DealReference==t1.DealReference))

end function


public function NonExtensions() '' .Net3.5 and above

  var result = from t1 in db.table1
               where !(from t2 in db.table2
                       select t2.DealReference)
                       .Contains(t1.DealReference)
               select t1

end function



内联(NonExtensions)方法很可能是错误的,对我来说效率很低.如果您使用的是4.0,则请遵循ByExtentions方法.如果没有,那么让我知道,我会再去一次

祝你好运^ _ ^



The inline (NonExtensions) method could well be wrong and look inefficient to me. If you are using 4.0 then stick with the ByExtentions menthod. If not then let me know and I''ll have another go

Good Luck ^_^


这篇关于Linq-左外连接两个数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆