Search code examples
c#arrayssortingicomparableicomparer

Generic IComparer for sorting different objects in different properties


I'm trying to sort an array of objects with IComparer.

I wrote the code but it works only with the particular object. e.g.:

for this class

public class Cars
{
    public string Name { get; set; }
    public string Manufacturer { get; set; }
    public int Year { get; set; }

    public Cars(string name, string manufacturer, int year)
    {
        Name = name;
        Manufacturer = manufacturer;
        Year = year;
    }
}

My code looks like:

class MySort 
{
    public class SortByYears : IComparer
    {
        int IComparer.Compare(Object x, Object y)
        {
            Cars X = (Cars)x, Y = (Cars)y;                
            return (X.Year.CompareTo(Y.Year));
        }
    }

    public class SortByName : IComparer
    {
        int IComparer.Compare(Object x, object y)
        {
            Cars X = (Cars)x, Y = (Cars)y;
            return (X.Name.CompareTo(Y.Name));
        }
    }

    public class SortByManyfacturer : IComparer
    {
        int IComparer.Compare(object x, object y)
        {
            Cars X = (Cars)x, Y = (Cars)y;
            return (X.Manufacturer.CompareTo(Y.Manufacturer));
        }
    }
}   

But if I add another class with different properties it will be useless.

So is there any chance to modify this code so that it worked for objects with different properties?


Solution

  • Use an interface and use generic IComparer Interface instead of IComparer

    public interface IObjectWithNameProperty
    {
        string Name {get; set;}
    }
    
    public class MyNameComparer : IComparer<IObjectWithNameProperty>
    {
        public int Compare(IObjectWithNameProperty x, IObjectWithNameProperty y)
        {
            ...
        }
    }
    
    public class Car: IObjectWithNameProperty
    {
         public string Name  {get;set;}
         ...
    }
    public class Dog: IObjectWithNameProperty
    {
         public string Name  {get;set;}
         ...
    }