Domanda

I have an interface named IEmployee. I need to implement the IComparer to the implementation of my interface.

Here is my code,

interface IEmployee
  {

      String Name {get;set;}
      DateTime DOB {get;set;}
  }

I have created a child class for this like

class Employee
  {

      String Name {get;set;}
      DateTime DOB {get;set;}
  }

Now i need to implement the IComparer to this, and in my Main i want to get the copmarer like

IComparer<IEmployee> comparerobject= // The comparer from the class.

And using this comparer i need to sort the collection of employee based on their names, like

var employees = new IEmployee[]{new Employee("....."),....}
Array.Sort<IEmployee>(employees , comparer);
È stato utile?

Soluzione

You could instead implement IComparable. Then your code could look something like:

interface IEmployee : IComparable
{
    String Name { get; set; }
    DateTime DOB { get; set; }
}

class Employee : IEmployee
{
    public string Name { get; set; }
    public DateTime DOB { get; set; }

    public int CompareTo(object obj)
    {
        return this.Name.CompareTo(((IEmployee)obj).Name);
    }
}

Then you can just sort the array as follows:

Array.Sort<IEmployee>(employees);

Altri suggerimenti

you can do

var sorted = employees.OrderBy(e => e.Name).ToArray();

or with a comparer

public class EmployeeComparer : IComparer<IEmployee>
    {
        public int Compare(IEmployee x, IEmployee y)
        {
            return x.Name.CompareTo(y.Name);
        }
    }

then Array.Sort(employees, new EmployeeComparer());

Is there a reason you want to use an IComparer? You have several options other than that.

First of all, you can use a Linq query as described by @Keith. That has some memory implications since a new IEnumerable must be allocated.

Perhaps your best option is to use the overload of the Sort method that takes in a Comparison object, which is just a delegate that compares two objects:

Array.Sort(employees, (a, b) => a.Name.CompareTo(b.Name));

If you really want to use IComparer, then you need to make a class that implements IComparer<IEmployee>:

public class EmployeeComparer : IComparer<IEmployee>
{
    public int Compare(IEmployee e1, IEmployee e2)
    {
        return e1.Name.CompareTo(e2.Name);
    }
}

And then use that for the Sort method. You could also make Employee itself implement IComparer if you so desired, but that is strange, since then it could really just implement IComparable.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top