Change object color c# nothing happens

I am am trying to change object color via grasshopper component.
I followed basic example, but following lines does change color of object:

(I am not adding new object I just want to modify color)

for (int i = 0; i < partitions.Count(); i++)  {
  Color c = Color.FromArgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255));
  IEnumerable<RhinoObject> rhinoO = partitions.ElementAt(i).Select(Rhino.RhinoDoc.ActiveDoc.Objects.Find);
     for (int j = 0; j < rhinoO.Count(); j++)     {
        rhinoO.ElementAt(i).Attributes.ObjectColor = c;
        rhinoO.ElementAt(i).Attributes.ColorSource = Rhino.DocObjects.ObjectColorSource.ColorFromObject;
        rhinoO.ElementAt(i).CommitChanges();
      }
  }

There is a problem with your counter index (i vs j) in the second loop.

But, I think you may also be “surprised” by the so-called late evaluation of LINQ operators. When you use a Select statement, nothing is selected until you evaluate the result. In this case, you evaluate it three times by rhinoO.ElementAt(i), and each time you get a fresh object copy. I advise to change like this:

for (int i = 0; i < partitions.Count(); i++)  {
  Color c = Color.FromArgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255));
  IList<RhinoObject> rhinoO = partitions.ElementAt(i).Select(Rhino.RhinoDoc.ActiveDoc.Objects.Find).ToList(); // by using ToList() you force an early evaluation of the Select statement
     for (int j = 0; j < rhinoO.Count(); j++)     {
        var obj = rhinoO[j]; // call the next three lines on the same object instance.
        obj.Attributes.ObjectColor = c;
        obj.Attributes.ColorSource = Rhino.DocObjects.ObjectColorSource.ColorFromObject;
        obj.CommitChanges();
      }
  }

I changed to j (this was a stupid mistake)
But it did not make any effect.

I was really surprised that only this helped:
var obj = rhinoO[j];

Thank you

I was not surprised :slight_smile: Like I said, many of the LINQ operators (like Select, Where, etc.) evaluate lazily. This is to speed up things in a complicated query. But the side effect is that you may get the operator to evaluate multiple times. And in this case, you get three times a different copy of the Rhino object.

Got it either use Ilist to force it or copy the variable. Och those dirty linq…