Purpose: To have multiple options to sort using properties of my class .
I managed to sort using samAccountName using Comparable but failed to correctly implement IComparer. But know I am getting an error specified below.
Error:Does not implement interface member System.Collections.Icomparer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace ActiveDirectory
{
public class sortLastName : IComparer
{
int IComparer.CompareTo(Employee oEmployee, Employee oEmployee2)
{
return String.Compare(oEmployee.lastName, oEmployee2.lastName);
}
public static IComparer sortYearAscending()
{
return (IComparer)new sortLastName();
}
}
//The code works great when I make a call like
// List<Employee> x = new List<Employee>();
// x.sort();// sorts by samAccountName
// Now I would like to figure out how to sort by lastName and still be able to sort by
//samAccountName if necceaary.
public class Employee :IComparable
{
//default sort order
public int CompareTo(object oEmployee)
{
Employee emp1 = (Employee)oEmployee;
return String.Compare(this.samAccountName, emp1.samAccountName);
}
public string lastName
{
get;
set;
}
public string samAccountName
{
get;
set;
}
}
}
you need to implement a method named “Compare” not “CompareTo” for your
sortLastName-class implementing IComparerthen you can sort by
x.Sortwith this overload:this is the implementation you should use:
(Note I didn’t change the name because you wouldn’t see the context any more but sortLastName is no good name for a comparer)