简体   繁体   English

使用linq内部连接C#数据表和Sql数据表

[英]Inner Join a C# datatable and Sql Datatable using linq

I know this is obviously a repeated question to ask but I am unable to figure out the issue, as I am new to LINQ. 我知道这显然是一个重复的问题,但是由于我是LINQ的新手,所以我无法弄清楚这个问题。

Basically I have to matchup for duplicate entry of data while adding multiple records at a time. 基本上,我必须对对数据的重复输入进行匹配,同时一次添加多个记录。 So, I have a Table in my database that has few rows and then I create DataTable dynamically which is clone(in terms of structure) of that table. 因此,我在数据库中有一个表,该表只有几行,然后动态创建DataTable ,该表是该表的克隆(就结构而言)。 Now dtDup is the Database Table, returned as dataset/datatable from a select query, and dupVals is the dynamic clone that is to be cross checked for duplicates 现在, dtDup是数据库表,从选择查询中作为数据集/数据表返回,并且dupVals是要进行重复检查以进行重复检查的动态克隆。

var CommnRows = 
    from dbA in dtDup.AsEnumerable()
    join appB in dupVals.AsEnumerable() on
    new { 
            MonthID = dbA.Field<int>("MonthID"), 
            UserID = dbA.Field<int?>("UserID"), //nullable int
            IsActive = dbA.Field<bool?>("IsActive"), //nullable bit
            Gender = dbA.Field<String>("Gender").ToString().ToUpper()
        } 
    equals
    new { 
            MonthID = appB.Field<int>("MonthID"), 
            UserID = appB.Field<int?>("UserID"), 
            IsActive = appB.Field<bool?>("IsActive")
            Gender = appB.Field<String>("Gender").ToString().ToUpper()
        }
    select dbA;

So, in case I have some rows returned then (I assume, that above join is correct inner join) this means that there are duplicate rows. 因此,如果我返回了一些行(假设以上联接是正确的内部联接),则意味着存在重复的行。

But I am getting an error: 但我收到一个错误:

Object reference not set to an instance of an object 你调用的对象是空的

at new after equals newequals

I found the issue. 我发现了问题。 I was trying to change the type of one of my column that was a string and at first I did not included in the question (now updated), but when I tried debugging it line by line, I found that it was breaking while near Gender . 我正在尝试更改属于字符串的一列的类型,起初我没有将其包括在问题中(现在已更新),但是当我尝试逐行调试它时,我发现它在Gender附近时正在断开。 So, just removed the ToString().ToUpper() from that area and it worked. 因此,只需从该区域删除ToString().ToUpper()

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

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