Cannot remove item from list

I’m trying to remove points which are close to each other, but it says

Collection was modified; enumeration operation may not execute

whatever I do: .Remove() or .RemoveAt()

  private void RunScript(List<Point3d> pts, double min, ref object A)
    foreach (Point3d pt1 in pts)
      foreach (Point3d pt2 in pts)
        if (pt1.DistanceTo(pt2) < min && pt1.DistanceTo(pt2) != 0){
    }[|attachment](upload:// (5.8 KB) 
    A = pts;
  } (5.8 KB)

You can’t run on a treadmill while you’re breaking it.

First, don’t use foreach in a nested loop that compares all with all in a single collection, use:

for(var i=0; i< pts.Count; i++)
  for(var j=i+1; j<pts.Count; j++)
    Print(i + ", " j); 

bc the distance(i, j) is the same as distance(j, i),

and to remove it, you can run the collection backwards (starting with the last one, although I’m not sure it works in this nested case) or instead of removing items, add to another list those you want to keep.


See attached as well (121.7 KB)

Update: well … the trad update (way faster), that is. (121.1 KB)