简体   繁体   中英

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.

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. 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

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

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 . So, just removed the ToString().ToUpper() from that area and it worked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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