用外部位置排序对象,有时用内部位置排序对象

本文关键字:排序 对象 位置 内部 外部 | 更新日期: 2023-09-27 18:08:46

我有两个类:

public class OuterObject
{
   public int OuterPosition { get; set; }
   public InnerObject InnerObject { get; set; }
}
public class InnerObject
{
   public int InnerPosition { get; set; }
}

我需要排序一个OuterObjects的列表:首先,在OuterPosition之后。然后,只有拥有InnerObject的outerobject,才应该排在它们的InnerPosition之后。

例如,如果我有四个OuterObjects:

A {OuterPosition = 1, new InnerObject {InnerPosition = 2}}
B {OuterPosition = 2}
C {OuterPosition = 3, new InnerObject {InnerPosition = 1}}
D {OuterPosition = 4}

我应该得到顺序:

C {OuterPosition = 3, new InnerObject {InnerPosition = 1}}
B {OuterPosition = 2}
A {OuterPosition = 1, new InnerObject {InnerPosition = 2}}
D {OuterPosition = 4}

有简单的方法来完成它吗?

用外部位置排序对象,有时用内部位置排序对象

这样的东西应该可以工作。

// First, order by outer position
var result = list.OrderBy(o => o.OuterPosition).ToList();
// Next, rearrange the items with inner objects
var outerPositions = result.Select((o, i) => new{i, o});
var withInner = outerPositions.Where(e => e.o.InnerObject != null).ToList();
var withInnerPositions = withInner.OrderBy(e => e.o.InnerObject.InnerPosition)
    .Select((e, i) => new{newPosition = withInner[i].i, e.o});
foreach(var p in withInnerPositions)
{
    result[p.newPosition] = p.o;
}
IEnumerable<OuterObject> result = source
  .OrderBy(obj => obj.OuterPostion)
  .OrderBy(obj => obj.InnerObject != null ? obj.InnerObject.InnerPosition : obj.OuterPosition)
   //the second OrderBy preserves the original order in the event of ties in the second.

IEnumerable<OuterObject> result = source
  .OrderBy(obj => obj.InnerObject != null ? obj.InnerObject.InnerPosition : obj.OuterPosition)
  .ThenBy(obj => obj.OuterPostion)
   //ThenBy breaks ties in the first order with sub-sorting.

这些可能不能给出问题中规定的顺序,但可以找到这些条件和order/ThenBy的一些安排来达到这个目的。