Emi
Emi

Reputation: 306

Sort a list of custom objects multiple times by different object properties in vb.net

I want to sort a list of custom objects by multiple object properties.

For example, I have:

MyObject.A
MyObject.B
MyObject.C

I want to sort the list first by the values of property "A", then by B and then by C. All those properties are strings(that may or may not be equal to each other and may or may not consist of/contain number characters).

After digging through web I found something that worked for the case where I only needed to sort the list by one property (by "A" in this example):

MyList.Sort(Function(x, y) x.A.CompareTo(y.A))

That worked fine.

So after that, I figured I just need to do more sorts in correct order and I tried doing something like this:

MyList.Sort(Function(x, y) x.C.CompareTo(y.C))
MyList.Sort(Function(x, y) x.B.CompareTo(y.B))
MyList.Sort(Function(x, y) x.A.CompareTo(y.A))

Which kinda sometimes works and sometimes doesn't. If there are few list entries (<10), it works fine and, for example, if "A" values are equal, the list is sorted by "B" values and if those are equal, then by "C". But, when I add more entries, it breaks down and only the last sort is correct. Seems that each next sort doesn't retain the original order of entries it doesn't need to sort.

How would I sort something like this?

Upvotes: 2

Views: 1672

Answers (1)

Joel Coehoorn
Joel Coehoorn

Reputation: 415840

MyList = (MyList.OrderBy(Function(i) i.A).
                 ThenBy(Function(i) i.B).
                 ThenBy(Function(i) i.C)).ToList()

As to why your existing method did not work: that's the difference between a stable and an unstable sort. According to MSDN, the Sort() method unstable.

Upvotes: 5

Related Questions