Search code examples
c#rhinograsshopper

C# Split lists simplify code


Goodmorning,

I'm coming from Python environment and turning to c#.

I'm splitting a wider list into narrower lists with a prescribed lenght.

Is there a way to simplify the following code? My guess is that it is a bit quite slow and not properly follows c# common coding rules.

List<object> B = new List<object>();
for(int i = 0; i < SD_Data.Count / 314; i++) {
  var SD_Input = SD_Data.Skip(314 * i).Take(314 * i + 313);
  B.Add(SD_Input);
}

A = B;

I've found this useful way

public static IEnumerable<IEnumerable<T>> Chunk<T > (this IEnumerable<T> source, int chunksize)
{
  while (source.Any())
  {
    yield return source.Take(chunksize);
    source = source.Skip(chunksize);
  }      
}
var z = Chunk(x, 10);

But it does raise the following error:

Error (CS1513): } expected (line 69)
Error (CS1518): Expected class, delegate, enum, interface, or struct (line 88)
Error (CS1518): Expected class, delegate, enum, interface, or struct (line 88)
Error (CS1518): Expected class, delegate, enum, interface, or struct (line 89)
Error (CS1518): Expected class, delegate, enum, interface, or struct (line 89)
Error (CS1518): Expected class, delegate, enum, interface, or struct (line 90)
Error (CS1518): Expected class, delegate, enum, interface, or struct (line 91)
Error (CS1518): Expected class, delegate, enum, interface, or struct (line 92)
Error (CS1518): Expected class, delegate, enum, interface, or struct (line 94)
Error (CS1001): Identifier expected (line 112)
Error (CS1001): Identifier expected (line 114)
Error (CS1022): Type or namespace definition, or end-of-file expected (line 115)

I'm working on the Grasshopper interface of Rhinoceros software from McNeel.

Thanks in advance!


Solution

  • I finally figured it out.

    This thread helped me a lot.

    Working with arrays/list with C# components in Grasshopper 3D

    The issue was raised since the method was defined inside another method, which is RunScript. The solution is to write it down in the

    // <Custom additional code>
    
    code here
    
    // <Custom additional code>
    

    so the result is:

     private void RunScript(List<Point3d> SrcPts, List<string> Instrument, List<object> SD_Data, List<double> XY_Angles, List<string> Octave, ref object A, ref object B)
      {
        B = Chunk(SD_Data, 314);
      }
    
      // <Custom additional code> 
    
      public static IEnumerable<IEnumerable<T>> Chunk<T > (IEnumerable<T> source, int chunksize)
      {
        while (source.Any())
        {
          yield return source.Take(chunksize);
          source = source.Skip(chunksize);
        }
      }
      // <Custom additional code>
    

    Thanks all for the valuable tips.