Is there a sorted collection type in .NET?

前端 未结 7 1671
夕颜
夕颜 2020-12-01 08:19

I\'m looking for a container that keeps all its items in order. I looked at SortedList, but that requires a separate key, and does not allow duplicate keys. I could also j

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-01 08:27

    Here's an old trick I used way back in VB6 to sort things alphabetically: Use a System.Windows.Forms ListBox object, and set its "Sorted" property to true. In C#, you can insert any object into the listbox, and it will sort the object alphabetically by its ToString() value:

    for a class module:


    using System.Windows.Forms;

        static void Main(string[] args)
        {
            ListBox sortedList = new ListBox();
            sortedList.Sorted = true;
    
            sortedList.Items.Add("foo");
            sortedList.Items.Add("bar");
            sortedList.Items.Add(true);
            sortedList.Items.Add(432); 
    
            foreach (object o in sortedList.Items)
            {
                Console.WriteLine(o);
            }
    
            Console.ReadKey();
        }
    

    This will display:

    432
    bar
    foo
    True

提交回复
热议问题