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

Time:01-14

I am trying to generate 10 random points in Grasshopper and add them to a list using the following code:

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;

  }

I couldn't execute the enumeration operation. I have searched a lot, but couldn't find a solution for a similar case with adding random unique elements to an iterating list.

CodePudding user response:

try this, your code can not be compiled, because of wrong using 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;

a variant without 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;
  •  Tags:  
  • Related