2

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?

1
  • the "< 10" issue sounds like you are expecting numerals to sort like numbers. "9" will always compare as more than "10" or "800" when it is a text sort Commented Aug 5, 2014 at 17:34

1 Answer 1

5
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.

Sign up to request clarification or add additional context in comments.

1 Comment

I can't use LINQ, any other solution?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.