Search code examples
c#icomparer

How to compare multiple object values against each other?


Assume i have a object with the following values in it (also please note i do not wish to use a datetime object for this, just the following values below and i wish to solve this in the comparer itself):

int year; 
int month; 
int day;
int sec;
int min;

How can i compare all those multiple values in my Comparer against each other so they get listed according date?

Then i wish to make a Comparer.cs class:

class MyComparer: IComparer
{
    int sort;

    public MyComparer(int s)
    {
        sort= s;
    }

    public int Compare(object x, object y)
    {
        Date d1 = (Date)x;
        Date d2 = (Date)y;
        int result= 0;

         // d1.Year.CompareTo(d2.Year);  //get accessors from other class
        // i seem to be limited here by comparing only 1 single value to a other?

        return result;
    }
}

}


Solution

  • Like this:

    int result = d1.Year.CompareTo(d2.Year);
    if (result != 0) return result;
    
    result = d1.Month.CompareTo(d2.Month);
    if (result != 0) return result;
    
    ...
    
    return 0;   //All properties were equal