2

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 need to sort list of objects. The objects in list are instances of Genome class. I overloaded operator < and operator > in that class.

 class Genome
{
    public List<double> weights;
    public double fitness;

    public Genome()
    {
        fitness = 0.0;
        weights = new List<double>();
    }

    public Genome(List<double> weights, double fitness) {
        this.weights = weights;
        this.fitness = fitness;
    }

    
    public static bool operator <(Genome lhs, Genome rhs)
    {
        return (lhs.fitness < rhs.fitness);
    }

    public static bool operator >(Genome lhs, Genome rhs) {
        return (lhs.fitness > rhs.fitness);
    }

}

This is how the population is declared:

List<Genome> population = new List<Genome>();

How can I sort this array? Can the operator overloaded operator be used < like in C++?

3 Answers 3

6
population.OrderBy(x => x.weights); 

or:

population.OrderByDescending(x => x.fitness); 
Sign up to request clarification or add additional context in comments.

1 Comment

Whole correct solution (I hope) is: population = population.OrderBy(x => x.fitness).ToList();
2

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

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

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

IComparable<T> 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<T> interface directly.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.