What's the Comparer class for?

后端 未结 7 1999
逝去的感伤
逝去的感伤 2021-02-07 00:02

What purpose does the Comparer class serve if the type that you specify already implements IComparable?

If I specify Comparer.Defaul

7条回答
  •  名媛妹妹
    2021-02-07 00:39

    public class Person
    {
        public string LastName;
        public string FirstName;
    
    }
    
    public class Class2
    {
        public void test()
        {
            List classList = new List();
            //add some data to the list
            PersonComparer comp = new PersonComparer();
            classList.Sort(comp);
        }
    }
    
    public class PersonComparer : Comparer
    {
    
        public override int Compare(Person x, Person y)
        {
            int val = x.LastName.CompareTo(y.LastName);
            if (val == 0)
            {
                val = x.FirstName.CompareTo(y.FirstName);
            }
            return val;
        }
    }
    

提交回复
热议问题