Showing results for 
Search instead for 
Did you mean: 
Copilot Lvl 2
Message 1 of 3

Sort a List of objects based on a Method (c#)

Solved! Go to Solution.

I'm quite new to coding and am trying to write code for an API for Revit in c#.


I have a List of Objects :  List<Element>

and a List of double : Dist<double>

Each double in Dist corresponds to an object in List in the same order.


I need to sort the List based on doubles from Dist.


this is an Api and I can't simply define a new property for object and sort by that property.


How can i do this? Is this possible with Linq, Query ?



2 Replies
Commander Lvl 2
Message 2 of 3

Re: Sort a List of objects based on a Method (c#)

It's not clear from your question if you need to sort in-place, or can return a new list of the sorted Elements.


I can think of several ways to do this, but they all require building a new data set and sorting that, to build a resulting sorted list of Element.

(the code below is pseudo-C#, I'm doing this off-the-cuff)

For instance, you would build a List<Tuple<double, int>> which is your second list (Dist?) and the index within the list, and then sort it: 

var sortlist = new List<Tuple<double,int>>();
for (int dex = 0; dex < Dist.Length; dex++)
    sortlist.add(new Tuple<double,int>(Dist[i], i);
sortlist.Sort((x, y) => y.Item1.CompareTo(x.Item1));

Now sortlist is sorted by your double values (Item1 in the tuple). You can then build a sorted list of Element because the sortlist tuple has the matching index.

var sortedElements = new List<object>();
for (int dex = 0; dex < sortlist.Length; dex++)
    sortedElements.add( originalElements[sortlist[dex].Item2 );

sortedElements is now a List<Element> which is sorted in Dist order. originalElements being your original List<Element>; Item2 in the tuple being the original index.


Maybe someone smarter than I can suggest a better approach.


Please follow-up to let us know how you made out. For good karma, mark a reply as the answer if it helped!

Copilot Lvl 2
Message 3 of 3

Re: Sort a List of objects based on a Method (c#)


i got the idea. Now i'll try to write the code