Sort array of object in C# (equivalent of std::sort)

前端 未结 3 890
离开以前
离开以前 2021-01-21 16:19

How can I sort array of strings ascending in c#, I want use something like std::sort in C++:

 std::sort(population.begin(), population.end())

I

3条回答
  •  耶瑟儿~
    2021-01-21 16:37

    The way that You are defining the order of objects (< and >) is not right for C#.

    You need to realize the IComparable interface. It has only one method:

    public interface IComparable
    {
       int CompareTo(object o);
    }
    

    The CompareTo method is used for comparing the object with some other object. It returns a number:

    1. less 0. The current object will be before the object which is in argument
    2. equals 0. Two objects are equal
    3. More than 0. Current object will be after the object which is in argument

    For example:

    class Paper: IComparable
    {
       public int width;
       public int height;
       public int CompareTo(object o)
       {
          Paper p = o as Paper;
          if (p!=null)
          {
              return this.width*this.height-p.width*p.height
          }
    }
    

    In Your case, You just need to return this.fitness-p.fitness.

提交回复
热议问题