views:

823

answers:

4

With ListView controls, you can specify a column to sort by, and there's a method to sort() whenever you want.

However, this only allows for single column sorting.

I'm keen to sort by say, Column A first, and then by Column F for when they are the same.

I've found a few custom compare classes written online, but wondered if stackoverflow could show a cleaner way. Plus having this here may help others looking for it in future :)

Any suggestions or examples on how to go about this appreciated.

A: 

Is this on the web or winform? On the web you can put together an expression that has the columns, comma separated, and pass it to the sort() method of the listview

Framework 3.5 and up though...

curtisk
Windows Form, thanks though
Mark Mayo
A: 

Well, if you just want the columns to be sorted, try using List of List; for instance like following:

List<List<string>> lstColumns = new List<List<string>>();

Haven't tried it, but just thinking a quick solution.

KMan
+1  A: 

As with almost all tasks, ObjectListView (an open source wrapper around .NET WinForms ListView) makes living with a ListView much easier.

ObjectListView has SecondarySortColumn and SecondarySortOrder properties to do exactly what you are asking.

If you want to do even fancier sorting, you can install a CustomSorter. Have a look at this recipe

Grammarian
+1  A: 

So, after playing around, the answer I came up with was to write a ListViewItemComparer class through the IComparer interface.

I then overwrote the Compare() method, and could now return -1, 0, or 1 depending on the comparison between first the primary column, and then when equal, the secondary column.

Quite tidy in the end, I think.

Mark Mayo