Chris Whisenhunt
Chris Whisenhunt

Reputation: 351

Ordering a list by two properties, ParentID and ChildID

I have a class that has 3 properties: Name, ID, and ParentID.

My data:

        Name       ID     ParentID
        Event A    1      1
        Event B    2      1
        Event C    3      1
        Event D    4      2

I have everything in a List and was trying to use the OrderBy or perhaps the Sort methods. Not sure which would be better.

I need the data in the list to be ordered so that an event has it's child as the next item in the list. Any help on this would be greatly appreciated, I am doing this in VB by the way. Thanks!!

Upvotes: 1

Views: 290

Answers (1)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112344

You can sort the list like this

list.Sort(Function(x, y) 2 * x.ParentID.CompareTo(y.ParentID) + _
                         x.ChildID.CompareTo(y.ChildID))

Explanation: I am using a lambda expression here. You can think of it as a kind of inline declaration of a function. CompareTo returns either -1, 0 or +1. A negative number means x is less than y, 0 both are equal and +1 means x is greater than y. By multiplying the first comparison by two, its sign takes precedence over the second comparison. The second has only an effect, if the first one returns 0.

The advantage of using the lists Sort method over LINQ is that the list is sorted in-place. With LINQ you would have to create a new list.

Upvotes: 2

Related Questions