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);
 }
}
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Oct 25, 2013 at 6:24
\$\endgroup\$
4
  • \$\begingroup\$ What version of .net framework is being used ? \$\endgroup\$ Commented Oct 25, 2013 at 7:33
  • \$\begingroup\$ Hi purnil, its 3.5 \$\endgroup\$ Commented Oct 25, 2013 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\$ Commented Oct 25, 2013 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\$ Commented Oct 28, 2013 at 4:39

1 Answer 1

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)
answered Oct 29, 2013 at 5:59
\$\endgroup\$
1
  • \$\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\$ Commented Oct 31, 2013 at 6:19

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.