table1
id | fileName | fileDateTime
1 | somefile | somedatetime
2 | somefile2 | somedatetime2
table2
id | fileName | fileDateTime
| somefile1 | somedatetime1
| somefile2 | somedatetime2
output table3
id | fileName | fileDatetime
| somefile1 | somedatetime1
I want to compare the 2 tables (column 2 & 3 only) and only have what is not in both tables, there is no ID field in the 2nd table. Then I plan on parsing the data in the file and add file info to database to record file has been parsed. I am having trouble comparing the 2 fields. This does not seem to work.
for (int i = 0; i < finalTable.Rows.Count; i++)
{
for (int r = 0; r < filesTable.Rows.Count; i++)
{
if (finalTable.Rows[i][2] == filesTable.Rows[r][2])
{
finalTable.Rows.Remove(finalTable.Rows[i]);
}
}
}
Assuming the value is a string, you could just do
for (int i = 0; i < finalTable.Rows.Count; i++)
{
for (int r = 0; r < filesTable.Rows.Count; i++)
{
if (finalTable.Rows[r].Field<string>(2) == filesTable.Rows[r].Field<string>(2))
{
finalTable.Rows.Remove(finalTable.Rows[i]);
}
}
}
If it's another type, just change the <string>
for the real type !
You can use Linq to achieve it as shown below.
Assuming your fields are string. For other datatype you can cast them accordingly:
using System.Data.Linq;
......
......
// Merge both tables data and group them by comparing columns values
dt1.Merge(dt2);
var g = dt1.AsEnumerable()
.GroupBy(x => x[0]?.ToString() + x[1]?.ToString()) // You can build Unique key here, I used string concatination
.ToDictionary(x => x.Key, y => y.ToList());
var unique = dt1.Clone();
foreach (var e in g)
{
if (e.Value.Count() == 1) // In either table - Intersaction
{
e.Value.CopyToDataTable(unique, LoadOption.OverwriteChanges);
}
if (e.Value.Count() == 2)
{
// In both tables -Union
}
}
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.