Click here to Skip to main content
15,884,388 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I have two foreach loops. One Foreach in other loop. How do i optimize those nested foreach loops

What I have tried:

C#
foreach (var t in ValidBCodes)
{
     foreach (var y in InsertRows)
     {
          var newRow = ds.Tables["FACT"].NewRow();
          newRow["S_ID"] = DestinationScenarioId;
          newRow["B_ID"] = t;
          newRow["G_ID"] = y["GLOBALFIELD_ID"];
          newRow["AMOUNT"] = y["AMOUNT"];

          ds.Tables["FACT"].Rows.Add(newRow);
      }
}
Posted
Updated 13-Mar-16 11:25am
v4
Comments
CHill60 13-Mar-16 16:15pm    
What are ValidBCodes and InsertRows and how are they related?
PIEBALDconsult 13-Mar-16 16:31pm    
Usually by not using foreach.
About all I can recommend is to not search for the table each time -- make a local variable to hold a reference to ds.Tables["FACT"] and use that.
You may also want to use column ordinals as well -- rather than column names.

1 solution

If newRow can't be reused, there is no optimization possible.
If newRow can be reused, I would rewrite the code this way.
C#
var newRow = ds.Tables["FACT"].NewRow();
foreach (var y in InsertRows)
{
	newRow["S_ID"] = DestinationScenarioId;
	newRow["G_ID"] = y["GLOBALFIELD_ID"];
	newRow["AMOUNT"] = y["AMOUNT"];
	foreach (var t in ValidBCodes)
	{
		newRow["B_ID"] = t;
		ds.Tables["FACT"].Rows.Add(newRow);
	}
}

[update]
If newRow can't be reused, simply swapping the loops allow the compiler to see that y["GLOBALFIELD_ID"] and y["AMOUNT"] are constant in the inner loop and move the reading of these values outside of inner loop.
C#
foreach (var y in InsertRows)
{
     foreach (var t in ValidBCodes)
     {
          var newRow = ds.Tables["FACT"].NewRow();
          newRow["S_ID"] = DestinationScenarioId;
          newRow["B_ID"] = t;
          newRow["G_ID"] = y["GLOBALFIELD_ID"];
          newRow["AMOUNT"] = y["AMOUNT"];
 
          ds.Tables["FACT"].Rows.Add(newRow);
      }
}
 
Share this answer
 
v3
Comments
CHill60 13-Mar-16 17:14pm    
Actually that was me making a mistake when I reformatted the OP's code :blush:
Sorry @VijayAkkaladevi
Patrice T 13-Mar-16 17:16pm    
Ok
Sascha Lefèvre 13-Mar-16 17:16pm    
A DataRow-object can't be reused to add multiple new DataRows to a DataTable, you get an ArgumentException "This row already belongs to this table". Please don't base solutions on assumptions, test them if you're not sure about it.
Patrice T 13-Mar-16 17:22pm    
Sorry, need to have C# to test :)
Sascha Lefèvre 13-Mar-16 17:25pm    
There you go:
https://www.visualstudio.com/en-us/products/visual-studio-community-vs.aspx
:p

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900