Search code examples
c#arraysicomparable

c# Sorting an array with IComparable Interface


I have a jobArray array with 5 jobs that contain a description, hours needed to complete, and an hourly pay that a user enters.

I need to sort the array when it prints by ascending order of the total fee (hours * hourly pay).

The assignment requires I use the IComparable interface when doing so but I'm unsure how to use it. Any help would be appreciated, thank you

Here is my job class

class Job : IComparable
{

    public Job(string description, int hours, double hourRate, double fee)
    {
        Description = description;
        hoursToComplete = hoursToComplete;
        hourlyRate = hourlyRate;
        totalFee = totalFee;

    }

This is the interface I've done to compare totalFees

    public int CompareTo(Job o)
    {
        int returnVal;
        Job temp = (Job)o;
        if (this.totalFee > temp.totalFee)
            returnVal = 1;
        else
            if (this.totalFee < temp.totalFee)
                returnVal = -1;
            else
                returnVal = 0;
        return returnVal;

    }

I'm unsure what do to from here as to sorting the jobs when they print out by total fees.


Solution

  • Here's the working version of your code:

    class Job : IComparable<Job>
    {
        public string Description { get; set;}
    
        public int HoursToComplete { get; set;}
    
        public double HourlyRate { get; set;}
    
        public double TotalFee { get; set;}
    
        public Job(string description, 
                   int hoursToComplete, 
                   double hourlyRate, 
                   double totalFee)
        {
            Description = description;
            HoursToComplete = hoursToComplete;
            HourlyRate = hourlyRate;
            TotalFee = totalFee;
        }
    
        public int CompareTo(Job otherJob)
        {
            int returnVal;
    
            if (this.TotalFee > otherJob.TotalFee)
                returnVal = 1;
            else
                if (this.TotalFee < otherJob.TotalFee)
                returnVal = -1;
            else
                returnVal = 0;
    
            return returnVal;
        }
    }
    

    Now since you have implemented IComparable<Job>, then on the given List<Job>, just call Sort, which will automatically call Job class CompareTo, instead of object class. Also note I have used the generic version IComparable<Job>, instead of IComparable, to avoid unncessary type-casting