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

前端 未结 3 857
离开以前
离开以前 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:35

    Unlike C++ which relies on operator< for sorting, C# relies on implementation of IComparable by your class, or takes an external comparer passed to Sort method:

    class Genome : IComparable {
        public int CompareTo(Genome other) {
            return fitness.CompareTo(other.fitness);
        }
    }
    

    Can operator overloaded for < be used, like in C++?

    IComparable is slightly more complex than <, because it returns zero when objects are equal. You can express the same logic using < and >, but it is easier to implement IComparable interface directly.

提交回复
热议问题