C#比较接口和排序

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 16:03   1067   0
    class Program
    {
        static void Main(string[] args)
        {
            TestClass t1 = new TestClass();
            t1.Score = 90;
            t1.Name = "lucy";
            TestClass t2 = new TestClass();
            t2.Score = 100;
            t2.Name = "lili";
            List<TestClass> mylist = new List<TestClass>();
            mylist.Add(t1);
            mylist.Add(t2);
            mylist.Sort(new CompareName());
            //mylist.Sort();
            for (int i = 0; i < mylist.Count; i++)
            {
                Console.WriteLine(mylist[i].Name);
                Console.WriteLine(mylist[i].Score);
            }

            Console.Read();
        }
    }
    class TestClass : IComparable<TestClass>
    {
        public int Score = 0;
        public string Name = string.Empty;

        public int CompareTo(TestClass other)
        {
            if (Score > other.Score)
            {
                return 1;
            }
            else if (Score == other.Score)
            {
                return 0;
            }
            else
            {
                return -1;
            }
        }
    }
    class CompareName :IComparer<TestClass>
    {
        //比较器

        public int Compare(TestClass x, TestClass y)
        {
            return x.Name.CompareTo(y.Name);
        }
    }

用泛型的比较接口和比较器接口。

比较接口 IComparable <>,比较器类接口: IComparer<>

sort() ;//比较接口排序

sor(比较器);//比较类排序

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP