订购具有外部和有时内部位置的对象

时间:2011-09-15 14:21:56

标签: c#

我有两个班级:

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

   public InnerObject InnerObject { get; set; }
}

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

我需要订购一个OuterObjects列表:首先,在OuterPosition之后。然后,只有具有InnerObject的OuterObjects应该在这些的InnerPosition之后排序。

例如,如果我有四个外部对象:

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}

有没有简单的方法来实现它?

2 个答案:

答案 0 :(得分:1)

这样的事情应该有效。

// 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;
}

答案 1 :(得分:0)

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.

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