c# List的排序

1.普通排序

list<int>
            List<int> x = new List<int>();
            x.Add(1);
            x.Add(11);
            x.Add(9);
            x.Add(8);
            x.Add(7);
            x.Add(6);
            x.Add(5);
            x.Add(2);
            x.Add(3);


            x.Add(3);
            x.Sort();
            for (int i = 0; i < x.Count; i++)
            {
                Console.WriteLine(x[i]);
            }
2.

     list<Item>如果Item类里面包含了Money成员变量,要对Money进行排序

      class Item : IComparable<Item>//比较的方法位于IComparable接口里面
    {
        public int money;
        public Item(int z)
        {
            this.money = z;
        }
        //重写接口里面的方法,如果传进去的数比里面的数打返回1负责返回-1,相等返回0
        public int CompareTo(Item other)
        {
            if(this.money>other.money)
            {
                return 1;
            }
            else
            {
                return -1;
            }
        }
    }
   

    List<Item> y = new List<Item>();
            y.Add(new Item(34));
            y.Add(new Item(14));
            y.Add(new Item(24));
            y.Add(new Item(1));
            y.Add(new Item(15));
            y.Add(new Item(341));
            y.Add(new Item(344));

            y.Sort();//对y集合进行排序
            for (int i = 0; i < y.Count; i++)
            {
                Console.WriteLine(y[i].money);
            }

猜你喜欢

转载自blog.csdn.net/m0_56283466/article/details/131551059