Custom listbox sorting

前端 未结 2 1092
一向
一向 2020-12-12 02:35

I need to sort the data contained within a number of listboxes. The user will be able to select between two different types of sorting using radio boxes, one of which is che

2条回答
  •  情书的邮戳
    2020-12-12 03:08

    The first algorithm is the same as alphabetic ordering, so you can use directly:

    int res = string.Compare(first,second);
    

    The second algorithm is descending alphabetic ordering of the last two chars:

    int res = -string.Compare(first.Substring(first.Length - 2, 2), second.Substring(first.Length - 2, 2));
    

    To sort the list you have two options; the first is to create your own ListBox subclass and override the Sort method as detailed on the MSDN page for ListBox.Sort Method.

    The second (easier and uglier) is to put all the items in a collection, order the collection and replace the items in the list, something like this:

    using System.Collections.Generic;
    using System.Windows.Forms;
    
    namespace WindowsFormsApplication1 {
        public partial class Form1 : Form {
    
            void SortListBox() {
                List items = new List();
                foreach (string value in listBox1.Items) {
                    items.Add(value);
                }
                items.Sort((first, second) => string.Compare(first, second));
                listBox1.Items.Clear();
                listBox1.Items.AddRange(items.ToArray());
            }
    
        }
    }
    

    Hope this helps...

提交回复
热议问题