Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# foreach within a foreach loop

Tags:

c#

I don't have too much experience with C# so if someone could point me in the right direction I would greatly appreciate it. I have a foreach loop that references a variable of an object. I wish to make another foreach loop inside the main one that compares (or performs actions on) the current variable to the rest of the variables in the array of the object. I have the following code:

// Integrate forces for each body.
    foreach (RigidBodyBase body in doc.Bodies)
    {
        // Don't move background-anchored bodies.
        if (body.anchored) continue;

        // This is where we will add Each Body's gravitational force 
        //  to the total force exerted on the object.

        // For each other body, get it's point and it's mass.

            // Find the gravitational force exterted between target body and looped body.
                // Find distance between bodies.
                    // vector addition
                // Force = G*mass1*mass2/distance^2
            // Find vector of that force.
            // Add Force to TotalGravityForce
        // loop until there are no more bodies.
        // Add TotalGravityForce to body.totalForce

    }
like image 631
Asrrin29 Avatar asked Dec 01 '08 17:12

Asrrin29


1 Answers

Each time you execute foreach, (even while nesting them) the internal Enumerator should "new" up a new iterator for you, there should not be any issue with that. The issues come about when you are adding, or removing items from the collection while you are still iterating...

Remember, in the inner foreach, to check to make sure you are not on the same item as the outer for each is on

  foreach( RigidBodyBase body in doc.Bodies)
     foreach ( RigidBodyBase otherBody in doc.Bodies)
         if (!otherBody.Anchored && otherBody != body)  // or otherBody.Id != body.Id -- whatever is required... 
              // then do the work here

by the way, the best place to put this code would be in a GravityForce property of the RigidBodyBase class, Then you could just write:

   foreach (RigidBodyBase body in doc.Bodies)
       body.TotalForce += body.GravityForce; 

although depending on what you're doing here (moving all objects?) they're may be even more opportunity for refactoring... I'd also consider having a separate property for the "other" forces, and have TotalForce Property do the summing of the Gravity Force and the "other" Forces?

like image 167
Charles Bretana Avatar answered Oct 04 '22 09:10

Charles Bretana