Simple key/value sorting in C# with RhinoCommon

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).

Thanks!

You can use Array.Sort() if you don’t mind turning your collections into arrays.

System.Array.Sort(keysArray, valuesArray);

4 Likes

To sort a collection by keys:

In my example I am sorting a list of points by their X coordinates:


using System.Linq;

 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, OrderBy OrderByDescending… etc. By using LINQ you can query, sort and filter data with great flexibility

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/

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

3 Likes

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.

2 Likes

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 List

3 Likes

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)