2
我需要根據預定義的uniqueIds對員工列表進行排序。基於預定義密鑰的自定義排序
簡單地說,考慮員工的ID的列表1 to 10 in random order.
我有一個預定義的規則說在2, 8, 1, 4, 6
如果爲了Employee對象的任何員工UID不在範圍內[1,10]把他們在最後清單...(任何訂單)。
我用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();
}
}
我已經能夠對列表進行排序,具有以下result-
(5, 7, 3), 2, 8, 1, 4, 6
==> 5,7,3沒有在參考項中列出,所以應該出現在最後,任何順序..
但是在我的參考鍵中找不到的項目,先排序。我需要把它們放在最後。
對於這樣的情況,是IComparer
,最好的方式去?
應該是'='而不是'==' – Kami
你是對的,謝謝。 – Servy
找不到item .. otherIndex將爲-1,但返回值將取決於評估'var thisIndex = referenceKeys.IndexOf(thisOne.UId);'。 – Abhijeet