I need to sort an employee list based on predefined uniqueIds.
In simple words, consider a list of employee Ids 1 to 10 in random order.
I have a predefined rule that says order employee objects in 2, 8, 1, 4, 6 And if any employee UId is not in range [1,10] put them at the end of list...(any order).
I wrote following code using IComparer<Employee>.
public class Employee
{
public int UId { get; set; }
public string Name { get; set; }
}
class Comparision : IComparer<Employee>
{
List<int> referenceKeys = new List<int> { 2, 8, 1, 4, 6 };
public int Compare(Employee thisOne, Employee otherOne)
{
var otherIndex = referenceKeys.IndexOf(otherOne.UId);
var thisIndex = referenceKeys.IndexOf(thisOne.UId);
if (thisIndex > otherIndex)
{
return 1;
}
else if (thisIndex < otherIndex)
{
return -1;
}
else
{
//if uid not found in reference list treat both employee obj as equal
return 0;
}
}
}
class CustomSorting
{
public static
List<Employee> employees = new List<Employee>
{
new Employee{UId=1, Name="Ram"},
new Employee{UId=2 , Name="Shyam"},
new Employee{UId=3 , Name="Krishna"},
new Employee{UId=4 , Name="Gopal"},
new Employee{UId=5 , Name="Yadav"},
new Employee{UId=6 , Name="Vishnu"},
new Employee{UId=7 , Name="Hari"},
new Employee{UId=8 , Name="Kanha"},
};
void sort()
{
employees.Sort(new Comparision());
}
static void Main()
{
new CustomSorting().sort();
}
}
I have been able to sort the list, with following result-
(5, 7, 3), 2, 8, 1, 4, 6 ==> 5, 7, 3 are not listed in reference key, so should appear in last, any order..
But items not found in my reference keys, are sorted first. I need to put them at the end.
For such a scenario, is IComparer, best way to go for ?