How to sort a DataGrid using stable sorting?

Viewed 1877

I've got a WPF DataGrid, and I've got it so that you can sort it by clicking on the column headers. It works, but it's unstable. How do I make it do stable sorting?

By this I mean, if I have this table:

Class    | Student    | Grade
-----------------------------
Art      | James      |  A
Art      | Amy        |  B
Art      | Charlie    |  A
Science  | James      |  D
Science  | Amy        |  A
Science  | Charlie    |  C
History  | James      |  B
History  | Amy        |  A
History  | Charlie    |  C

If I sort by student, it works like you'd expect:

Class    | Student    | Grade
-----------------------------
Art      | Amy        |  B
Science  | Amy        |  A
History  | Amy        |  A
Art      | Charlie    |  A
Science  | Charlie    |  C
History  | Charlie    |  C
Art      | James      |  A
Science  | James      |  D
History  | James      |  B

But if I now sort by class:

Class    | Student    | Grade
-----------------------------
Art      | James      |  A
Art      | Amy        |  B
Art      | Charlie    |  A
History  | James      |  B
History  | Amy        |  A
History  | Charlie    |  C
Science  | James      |  D
Science  | Amy        |  A
Science  | Charlie    |  C

It's destroyed the sort order of the students (unstable sorting). What I want is stable sorting, where it preserves the order:

Class    | Student    | Grade
-----------------------------
Art      | Amy        |  B
Art      | Charlie    |  A
Art      | James      |  A
History  | Amy        |  A
History  | Charlie    |  C
History  | James      |  B
Science  | Amy        |  A
Science  | Charlie    |  C
Science  | James      |  D

Seems like it should work like this by default, or at least be a toggle. Does anyone have any suggestions? @Eirik's idea of shift-clicking works, and that shows that the behaviour is present. However, what I'd really like is for to work like that without any modifiers. It shouldn't be a cause of "sort by this, then this, then this", it should be case of swapping the algorithm for a different one.

See this: http://en.wikipedia.org/wiki/Sorting_algorithm#Stability

2 Answers
Related