1
\$\begingroup\$

I have this code which compares data from two data tables. It does this by using a primary column and inserting the new record from table2 to table1. This loop continues for a large number of tables. I want to optimize it. Kindly give suggestions.

foreach (DataRow drRow in table2.Rows)
{
    if(!table1.Rows.Contains(drRow["KeyId"]))
    {
        table1.ImportRow(drRow);
    }
}
\$\endgroup\$
  • \$\begingroup\$ What version of .net framework is being used ? \$\endgroup\$ – Purnil Soni Oct 25 '13 at 7:33
  • \$\begingroup\$ Hi purnil, its 3.5 \$\endgroup\$ – rrk Oct 25 '13 at 8:22
  • \$\begingroup\$ I think that this might be the best way to do it. I have done a little bit of looking and it seems like the other ways that I have thought about doing it fall short of this code. \$\endgroup\$ – Malachi Oct 25 '13 at 13:50
  • \$\begingroup\$ Malachi, thanks a lot for looking into it. I too trying to find other way which will be more optimized. \$\endgroup\$ – rrk Oct 28 '13 at 4:39
1
\$\begingroup\$

For .net framework 3.5, you can have following code improvements:

foreach (var drRow in table2.Rows.Cast<DataRow>()
                      .Where(drRow => !table1.Rows.Contains(drRow["KeyId"]))) 
{
    table1.ImportRow(drRow); 
}
  1. part of body can be converted to LINQ-expression
  2. use "var" (implicitly typed) instead of "DataRow" (explicitly typed)
\$\endgroup\$
  • \$\begingroup\$ Hi Purnil,I tried and i was not able to see any improvement in performance. In fact the old code was faster. Anyways thanks for your inputs :) \$\endgroup\$ – rrk Oct 31 '13 at 6:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.