Very amateur C# question about setting Z value of a Point3d

List < Point3d > scaledPts = new List{pt1,pt2,pt3};
foreach(Point3d scaledpt in scaledPts)
{
scaledpt.Z += 2;
}

I would like to add 2 to the Z value of all the points in list. how do I do that?

Error

Error (CS1654): Cannot modify members of ‘scaledpt’ because it is a ‘foreach iteration variable’ (line 94)

variables in foreach are locked, use a for loop instead:

List < Point3d > scaledPts = new List{pt1,pt2,pt3};
for(int i = 0; i < scaledPts.Count; i++)
{
scaledPts[i].Z += 2;
}
Point3d pt1 = new Point3d(0.0, 2.0, 6.0);
Point3d pt2 = new Point3d(12.0, 6.0, 6.0);
Point3d pt3 = new Point3d(5.0, 14.0, 14.0);

List < Point3d > pts = new List<Point3d>{pt1, pt2, pt3};

for(int i = 0; i < pts.Count; i++)
{
  pts[i].Z += 2;
}
A = pts;

I tried. Still not working

Apologies @Wiley

use the below

Point3d pt1 = new Point3d(0.0, 2.0, 6.0);
    Point3d pt2 = new Point3d(12.0, 6.0, 6.0);
    Point3d pt3 = new Point3d(5.0, 14.0, 14.0);

    List < Point3d > pts = new List<Point3d>{pt1, pt2, pt3};

    for(int i = 0; i < pts.Count; i++)
    {
      Point3d pt = pts[i];
      pt.Z += 2;
      pts[i] = pt;

    }
    A = pts;
3 Likes

Point3d is a struct, not a class. So when you get the variable from the list, it gets automatically copied on the stack, you don’t get a reference. That is why you need to re-assign it to the list, so after modification it gets copied into the list again.

4 Likes

@menno thanks
I see so I cannot set property directly with Structure.

Just for my curiosity and education.
Is there a neater way to do it with Where/Select using System.Linq?

you could also move them with a Vector:

private void RunScript(List<Point3d> pts, ref object A)
  {
    for (int i = 0; i < pts.Count; i++)    
			 pts[i]+= new Vector3d(0, 0, 2);          
    A = pts;
  }
2 Likes

If you could use Point3dList instead of List<Point3d> you could do this:

Point3dList scaledPts = new Point3dList{pt1,pt2,pt3};
list.Transform(Transform.Translation(0,0,2));

Point3dList is defined in RhinoCommon, see below for documentation
Point3dList Class

6 Likes