I have two datatables and I want to get the difference between these two databases based on different columns and copy them to another datatable.
For example
datatable 1
Code | Name | Age | Money |
---|---|---|---|
123 | User1 | 25 | 68000.00 |
456 | User2 | 32 | 23000.00 |
963 | User3 | 56 | 75000.00 |
852 | User4 | 29 | 13000.00 |
datatable 2
Code | Name | Age | Money |
---|---|---|---|
963 | User3 | 56 | 75000.00 |
456 | User2 | 32 | 26000.58 |
123 | User1 | 25 | 59000.63 |
852 | User4 | 29 | 13000.00 |
741 | UserN | 22 | 15000.56 |
datatable result
Code | Name | Age | Money |
---|---|---|---|
456 | User2 | 32 | 26000.58 |
123 | User1 | 25 | 59000.63 |
741 | UserN | 22 | 15000.56 |
I use this code but it does not show the correct result
dtr = (from r in dt1.AsEnumerable()
where !dt2.AsEnumerable().Any(r2 => r[3].ToString().Trim() == r2[3].ToString().Trim())
select r).CopyToDataTable();
You can use Linq and Except
to determine:
In the example I am projecting the rows to anonymous types then doing the "except" set operation to obtain the result:
var dtrows = dt1.AsEnumerable().Select(rw => new { Code = rw[0], Name = rw[1], Age = rw[2], Money = rw[3] });
var dt2rows = dt2.AsEnumerable().Select(rw => new { Code = rw[0], Name = rw[1], Age = rw[2], Money = rw[3] });
dt2rows.Except(dtrows)
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.