\$\begingroup\$
\$\endgroup\$
4
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
-
\$\begingroup\$ What version of .net framework is being used ? \$\endgroup\$Purnil Soni– Purnil Soni2013年10月25日 07:33:58 +00:00Commented Oct 25, 2013 at 7:33
-
\$\begingroup\$ Hi purnil, its 3.5 \$\endgroup\$rrk– rrk2013年10月25日 08:22:00 +00:00Commented 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\$Malachi– Malachi2013年10月25日 13:50:44 +00:00Commented 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\$rrk– rrk2013年10月28日 04:39:15 +00:00Commented Oct 28, 2013 at 4:39
1 Answer 1
\$\begingroup\$
\$\endgroup\$
1
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);
}
- part of body can be converted to LINQ-expression
- use "var" (implicitly typed) instead of "DataRow" (explicitly typed)
answered Oct 29, 2013 at 5:59
-
\$\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– rrk2013年10月31日 06:19:32 +00:00Commented Oct 31, 2013 at 6:19
lang-cs