是否有解决方法可以将随机元素添加到 C# 中的迭代列表?

Is there is a work around to add random elements to iterating list in C#?

我正在尝试在 Grasshopper 中生成 10 个随机点并使用以下代码将它们添加到列表中:

private void RunScript(object x, object y, ref object A)
{

    List<Point3d> pts = new List<Point3d>();
    //List<Point3d> temp = new List<Point3d>();

    Point3d origin = new Point3d(20, 20, 0);
    pts.Add(origin);
    //temp.Add(origin);
    Random r = new Random();
    int i = 0;
    while (i < 10){
      Point3d pt_temp = new Point3d(r.Next(20, 30), r.Next(20, 30), 0);
      foreach (Point3d p in pts){
        if (p != pt_temp){
          pts.Add(pt_temp);
          i++;
        }else{
          break;
        }

      }

    }
    A = pts;

  }

我无法执行枚举操作。我进行了很多搜索,但找不到将随机唯一元素添加到迭代列表的类似案例的解决方案。

试试这个,你的代码无法编译,因为使用 foreach 错误

    List<Point3D> pts = new List<Point3D> { new Point3D(20, 20, 0)};

    Random r = new Random();
    int i = 0;
    while (i < 10)
    {
        Point3D pt_temp = new Point3D(r.Next(20, 30), r.Next(20, 30), 0);
        if (pts.Any(p => p == pt_temp)) continue;
        pts.Add(pt_temp);
        i++;
    }
 A = pts;

没有 linq 的变体

    List<Point3D> pts = new List<Point3D> { new Point3D(20, 20, 0) };

    Random r = new Random();
    int i = 0;
    while (i < 10)
    {
        Point3D pt_temp = new Point3D(r.Next(20, 30), r.Next(20, 30), 0);
    
        var exist = false;
        foreach (var item in pts) { if (item == pt_temp) exist = true; break; }
        if (exist) continue;

        pts.Add(pt_temp);
        i++;
    }
 A = pts;

嗯,解决此类问题的规范方法是在这种特殊情况下使用 Set、HashSet。 Set 将保证元素的唯一性

沿线(未经测试!)

var r = new HashSet<PointD>();
while (r.Count < 10) {
    r.Add(new Point3D(......));
}
return r;