Grasshopper c# get item from list

Hi all,

I am very new to c# grasshopper scripting and just getting started. I wanted to know - given a tree input, how would you retrieve the first item in each branch?

private void RunScript(DataTree<object> x, ref object A)
  {
  
    List<double> firstEntry = new List<double>();
    
    for( int i = 0; i < x.BranchCount; i++){
      
      if(i == 0){
        double tempNum = // something goes here to get the object at the right branch, path or index!
          firstEntry.Add(tempNum);
          }
      }
    A = firstEntry;
    }
    
  }

An example scenario might look like this :

private void RunScript(DataTree<object> x, ref object A)
{
	List<double> firstEntry = new List<double>();
	for( int i = 0; i < x.BranchCount; i++)
	{
		firstEntry.Add(x.Branches[i][0]);
	}
	A = firstEntry;
}

230308_get_first_item.gh (6.9 KB)

-Kevin

You don’eed C# to do that:


private void RunScript(DataTree<object> x, ref object A)
{
    List<double> firstEntry = new List<double>();
    
    for (int i = 0; i < x.BranchCount; i++)
    {
        double tempNum = (double)x.get_Item(new GH_Path(i))[0];
        firstEntry.Add(tempNum);
    }
    
    A = firstEntry;
}

//This code creates a new list to hold the first item of each branch. It then iterates over each branch using the BranchCount property of the data tree. For each branch, it uses get_Item to retrieve the first item in that branch using the branch path and index (0). It casts the object to a double (assuming that the data type in each branch is a double), and adds it to the firstEntry list. Finally, it sets the output parameter A to the firstEntry list.

@farouk.serragedine

This line of your code:

        double tempNum = (double)x.get_Item(new GH_Path(i))[0];

Causes this error:

  1. Error (CS0571): ‘DataTree.this[GH_Path, int].get’: cannot explicitly call operator or accessor (line 59)

The cannot explicitly call operator or accessor error can be corrected by changing the code to:

        double tempNum = x[new GH_Path(i), 0];
  • But this only works if you input DataTree is simplified:
    • works with tree structure {0}, {1}, {2}, …
    • fails with tree structure {0;0}, {0;1}, {0;2}, …

This works regardless of the input DataTree structure:

        double tempNum = x[x.Paths[i], 0];

Or you could simply use the solution I posted previously.

-Kevin

Cheers @kev.r - this is what I was looking for!
Also good to know about the approach below :zap: :zap:

Hey @Macuso ,

Cheers for your reply - I was trying to solve something else, but this was a simplified version of that scenario. It was more getting my head around the syntax than anything :slight_smile: