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){
          pts.Remove(pt2);
          //pts.RemoveAt(1);
          //pts.RemoveAt(-2);
        }
      }
    }[reduce_the_density.gh|attachment](upload://fXobW5ZDWB80hrIVpGk5ou8CjGt.gh) (5.8 KB) 
    A = pts;
  }

reduce_the_density.gh (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.

And…

See attached as well

Points_FilterByDistance_V1.gh (121.7 KB)

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

Points_FilterByDistance_V1A.gh (121.1 KB)

2 Likes