سؤال

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();
هل كانت مفيدة؟

المحلول

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)

نصائح أخرى

Your function should contain only one line:

return (a as ListViewItem).SubItems[0].Text.CompareTo((b as ListViewItem).SubItems[0].Text)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top