how to divide list of points into lists based on each point's X-coordinate or Y-coordinate?

166 views Asked by At

I am very new to C# so bear with me. I am writing a c# script inside rhino grasshopper, where I have created a list of points of the same colored pixels of an image. I am wondering if there is any way to sort and split the list into more lists based on the x or y coordinate of the points? For example, all points with the X-coordinate will be sorted into one list, so there will be a list of rows of the points.

public List<Point3d> SitePt(string imgPath, Color myColor)
    {
      Bitmap siteImg = new Bitmap(imgPath);
      List<Point3d> sitePx = new List<Point3d>();

      for (int i = 1; i < siteImg.Width - 1; i++)
      {
        for (int j = 1; j < siteImg.Height - 1; j++)
        {
          Color c = siteImg.GetPixel(i, j);
          if(myColor.Equals(c))
          {
            Point3d p = new Point3d(i, j, 0);
            sitePx.Add(p);
          }
        }
      }
      return sitePx;
}

I am not familiar with what I can do with lists, so I don't know whether I should use the group-by method.

1

There are 1 answers

2
Rufus L On

If I understand you correctly, you can use the GroupBy method to group the list into parts that have a common key, such as an X or Y coordinate:

List<Point3d> bluePoints = SitePt(imgPath, Color.Blue)

// Group the list by the `X` coordinate of each point:
IEnumerable<IGrouping<double, Point3D>> bluePointGroupsByX = 
    bluePoints.GroupBy(point => point.X);

foreach (IGrouping<double, Point3D> blueGroup in bluePointGroupsByX)
{
    Console.WriteLine("Here are the points with X coordinate = " + blueGroup.Key);
            
    Console.WriteLine(string.Join(", ", blueGroup));
}