0

Given I have a list of objects.

These objects have a property if ID

So var obj = new Object();
obj.ID = 1;

Now these objects have preceding objects, the preceding objects are linked by ID

Like this:

var obj1 = new Object();
var obj2 = new Object();
var obj3 = new Object();
var obj4 = new Object();
var obj5 = new Object();

obj5.precedingObjectId = obj4.Id;
obj4.precedingObjectId = obj3.Id;
obj3.precedingObjectId = obj2.Id;
obj2.precedingObjectId = obj1.Id;

As you can see, each object is linked to the object before it. object2 has a preceding object of object1.

The object names named incrementally is so just for purposes of explanation so i can not order by name.

Now I have a list of these objects jumbled up. So I need to order by preceding object. If object2 has a preceding object of object1 then object1 should come before object2 in the List

Is there a way to do this?

user1809104
  • 707
  • 2
  • 8
  • 26
  • What exactly are you attempting to accomplish? Check this question out http://stackoverflow.com/questions/188141/list-orderby-alphabetical-order – Greg Sep 15 '14 at 17:58
  • That question does not solve my problem. I can not sort my any property of the object. if one object is a preceding object of another the preceding object must come before in the list – user1809104 Sep 15 '14 at 18:02

1 Answers1

3

It's simple enough to do if you create a lookup from each Id to the children of that ID value.

Once you have that lookup you can start out with the object that has no preceding object, and then get the object that the "current" object precedes, until you get nothing.

public static IEnumerable<Foo> Order(IEnumerable<Foo> sequence)
{
    var lookup = sequence.ToLookup(foo => foo.precedingObjectId);

    var current = lookup[null];
    while (current.Any())
    {
        var foo = current.Single();
        yield return foo;
        current = lookup[foo.Id];
    }
}
Servy
  • 202,030
  • 26
  • 332
  • 449