简体   繁体   English

如何按只能在排序过程中获得的值对列表进行排序?

[英]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> .假设我有一个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.我想按属性 X 对其进行排序。如果有多个具有相同 X 值的对象,我想通过GetSomeValue(objectsWithSameXValue)对它们进行排序,它返回某个操作的值。 Said return value is calculated using all objects with equal value of X.所述返回值是使用具有相等 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().一切都按 X 排序。Item2、item3 和 item4 也按 GetSomeValue() 排序。

Is there anything I can do without huge if...else trees?如果没有巨大的 if...else 树木,我能做些什么吗? I tried different approaches, but sooner or later I got lost because it became confusing.我尝试了不同的方法,但迟早我迷路了,因为它变得混乱。

I would try doing the following:我会尝试执行以下操作:

  1. Grouping the values by X按 X 对值进行分组
  2. Sort the list of groups by their key按组的键对组列表进行排序
  3. Sort the values within each group by GetSomeValue(group)通过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.如果您可以选择,我建议将GetSomeValue(List<MyClass> values)更改为GetSomeValue(IEnumerable<MyClass> values) ,这样您就不必重复调用.ToList()了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM