Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a list by values which can only be gained during the sort process?

public class MyClass
{
    public int X { get; }

    public int GetSomeValue(List<MyClass> values)
    {
        return valueOfOperation;
    }
}

Let's say I have a List<MyClass>. I want to sort it by property X. If there are multiple objects with same value of X, I want to sort those by GetSomeValue(objectsWithSameXValue) which returns a value of some operation. Said return value is calculated using all objects with equal value of X.

Desired result should look like this:

Object    Property X    GetSomeValue({item2, item3, item4})
item1         1          
item2         3              2
item3         3              3
item4         3              9
item5         4              

Everything is sorted by X. Item2, item3 and item4 are also sorted by GetSomeValue().

Is there anything I can do without huge if...else trees? I tried different approaches, but sooner or later I got lost because it became confusing.

like image 765
BeNes Avatar asked Dec 02 '25 04:12

BeNes


1 Answers

I would try doing the following:

  1. Grouping the values by X
  2. Sort the list of groups by their key
  3. Sort the values within each group by GetSomeValue(group)
  4. Combine the results back into one big list
items.GroupBy(item => item.X)
    .OrderBy(group => group.Key)
    .SelectMany(group => group.OrderBy(item => item.GetSomeValue(group)))
    .ToList()

I'd suggest changing GetSomeValue(List<MyClass> values) to GetSomeValue(IEnumerable<MyClass> values) if you have the option, so you don't have to call .ToList() repeatedly.

like image 90
Andrew Williamson Avatar answered Dec 04 '25 18:12

Andrew Williamson