Anurag
Anurag

Reputation: 572

Compare 2 data tables with a condition

I have a DataTable dtA, with the below records:

ColumnA  ColumnB
1001     ARCH
1001     ARCH
1002     CUSS
1003     ARCH

And another DataTable dtB with records as below:

ColumnA
ARCH
CUSS

I need to compare both the DataTables as such, if there is ARCH in dtB, search for ARCH in dtA, when the first occurrence of ARCH is found in dtA, stop the search further and write to a Log.

If ARCH is not present in dtA, then take the 2nd record of dtB, which is CUSS, when the first occurrence of CUSS is encountered in dtA, stop the search further and write to the Log.

I tried it using DataTable.Select() method but wasn't able to successfully do it.

Experts please help.

EDIT:

bool flag = true; 
for (int counter = 0; counter < dtB.Rows.Count; counter++) 
{ 
var contains = dtA.Select("ColumnB = '" + dtB.Rows[counter][0].ToString() + "'"); 
if (contains.Length == 0 && flag == true) 
{ 
dtLogs.Rows.Add("CostCode not present in the Excel");
 flag = false; 
break; 
} 
}

Regards

Upvotes: 0

Views: 59

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460028

You could use a HashSet as efficient lookup collection which i'd use if you need it more than once:

var lookup = new HashSet<string>(dtA.AsEnumerable().Select(r => r.Field<string>("ColumnB")));
foreach(DataRow row in dtB.Rows)
{
    string value = row.Field<string>("ColumnA");
    if(lookup.Contains(value))
    {
        // write to log
    }
}

You could also use Enumerable.Contains which needs less memory but more CPU cycles:

var allBinA = dtA.AsEnumerable().Select(r => r.Field<string>("ColumnB"));
foreach (DataRow row in dtB.Rows)
{
    string value = row.Field<string>("ColumnA");
    if (allBinA.Contains(value))
    {
        // write to log
    }
}

Upvotes: 2

Related Questions