Total noob question, but can anyone explain how to sort the items in one list (values) using the items in another list (keys)? Must use RhinoCommon in C#. All I want to do is mimic the Sort List component in Grasshopper. Can’t make heads or tails of the documentation.
Would also be great to see how to sort the items in one list by itself (int and string).
You can use Array.Sort() if you don’t mind turning your collections into arrays.
To sort a collection by keys:
In my example I am sorting a list of points by their
private void RunScript(List<Point3d> x, object y, ref object A)
var l = x.Select(a => a.X).ToList();
A = Sort(x, l);
// <Custom additional code>
public List<Point3d> Sort(List<Point3d> dataToSort, List<double> dataToSortWith)
// Create Key value List
var keyValueList = new List<KeyValuePair<double, Point3d>>();
// add data to key value list
for (int i = 0; i < dataToSort.Count; i++)
keyValueList.Add(new KeyValuePair<double, Point3d>(dataToSortWith[i], dataToSort[i]));
// sort list based on key values
keyValueList.Sort((a, b) => (a.Value.CompareTo(b.Value)));
return keyValueList.Select(a => a.Value).ToList();
There are other methods that work on single
Lists such as
Sort as @Dani_Abalde pointed out,
OrderByDescending… etc. By using LINQ you can query, sort and filter data with great flexibility
There is also a nice data structure in C# called
KeyValuePair that is intended to sort a list with the data of another list.
PS: I am not even sure if this is the most computationally optimal solution to do this
I’ll just add that this is a good example of understanding you don’t always need Rhinocommon but should also be aware of the methods of the language you are using. Typically if what you are trying to do is not geometry / display / transformation / etc. related then the answer won’t be in Rhinocommon, especially when it comes to math, sorting, and array / list editing.
Yup, the world of programming is vast, just remember that RhinoCommon, was built for developers to interface with Rhinoceros. Most of the time, the most meaningful problems, or questions you can encounter will be outisde of the scope of RhinoCommon, and instead will belong to a much lower level approach, or will be language specific, aka sorting a
Thanks Dani! Works like a charm. I’m attaching a little snippet for the next hopeless noob that comes across this thread gets confused about .Sort() returning void.
SimpleSorting.gh (9.8 KB)