Grasshopper

algorithmic modeling for Rhino

Hi,

Is there a quick way to convert different types of nested Lists to dataTree :

    List<List<Line>>  -> DataTree
    List<List<int>> -> DataTree
    List<List<otherTypes>> -> DataTree

Views: 2318

Replies to This Discussion

There isn't for trees in GH1.

try this:

DataTree<T> ListOfListsToTree<T>(List<List<T>> list){
   DataTree<T> tree = new DataTree<T>();
   int i = 0;
   foreach(List<T> innerList in list){
      tree.AddRange(innerList, new GH_Path(new int[]{0,i}));
      i++;
   }
return tree;
}

Setting it up as a generic (the <T> thing) makes it easy to call on a List<List<Whatever>>  - it will just spit back a DataTree<Whatever> based on the type of the input you supply. 

Dear Andrew,

Thank you this function it is very useful. As working with datatrees this is a common issue that I always bump into when I have to write loops to made each datatree for each type.

Due to my C# I do not entirely understand this <T> thing but it works like a charm.

This <T> thing is called a generic class or a template. It means you write code which doesn't use a specific type such as Curve or string, but instead you use T everywhere. Then, when the class is used you have to tell it what you want T to be. This allows you to write a single class that can handle all kinds of types without loss of type-safety.

Most famous is the List<T> class, which is a collection class that can store anything. When you create a new instance of List<T> specifically for strings, you'd create a List<string>.

It's easiest to just think of this as a search-replace of T and your final type in the code.

Would it be possible to do the same with arrays of arrays?

In general I'd recommend against the use of multi-dimensional arrays. Anywhere. Multidimensional arrays require contiguous memory to be stored in, and memory usage goes up quick when you increase the number of dimensions. Nested/Jagged arrays can be stored over all the place. Another benefit of jagged arrays is that they can share sub-arrays. Depending on situation, that may drastically reduce memory usage as well.

So, string[][] is my preferred type, instead of string[,]

I guess the only exception to this would be if you are going to have loads and loads of these arrays and they're all rather small. In that case it may pay to have fewer type instances to deal with.

RSS

About

Translate

Search

Photos

  • Add Photos
  • View All

Videos

  • Add Videos
  • View All

© 2024   Created by Scott Davidson.   Powered by

Badges  |  Report an Issue  |  Terms of Service