0

I want to sort ListView items by the content of second column (which can be either "Online" or "Offline"). Sorting will be done only in one specific place in code, so the solution doesn't have to be flexible. More than that, it should be easy to implement and not requiring major changes in rest of application.

I tried to make class implementing IComparer and assign it to listView.ListViewItemSorter, but it doesn't work for me.

Code sample:

class ChannelSorter : System.Collections.IComparer
{
    public int Compare(object a, object b)
    {
        if ((a as ListViewItem).SubItems[0].Text.CompareTo("Online") == 0)
            if ((b as ListViewItem).SubItems[0].Text.CompareTo("Online") == 0)
                return 0;
            else
                return -1;
        else if ((b as ListViewItem).SubItems[0].Text.CompareTo("Online") == 0)
            return 1;
        else
            return 0;
    }
}


// in constructor of Form1
listView1.ListViewItemSorter = new ChannelSorter();
1
  • You forgot to (re)assign the Sorting property. Commented Jun 27, 2012 at 21:14

2 Answers 2

1

You can use LINQ, with the OrderBy method:

I suppose your users in the list are coming from an User[] array or a List, or any Enumerable. You then simply use the OrderBY method to get a new ordered List:

var currentUsers = new List<User>();
// Fill your users
// Super happy fun sorting time!
var sortedUsers = currentUsers.OrderBy(user => user.State);

Where user.State is their current state (Online, Offline)

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

2 Comments

"Users"... What made you think it's about users? ;) Anyway, that works. Thanks a lot!
I would have suggested Penguins or Servers, but I liked the human side of the thing :)
0

Your function should contain only one line:

return (a as ListViewItem).SubItems[0].Text.CompareTo((b as ListViewItem).SubItems[0].Text)

Comments

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.