2012-11-30 48 views
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,最好的方式去?

回答

4

var otherIndex = referenceKeys.IndexOf(otherOne.UId);將返回-1如果找不到該項目,該項目將小於任何找到的值。

你希望所有未找到的項目比任何發現的價值越大,所以只需添加:

if(otherIndex == -1) otherIndex = int.MaxValue; 
if(thisIndex == -1) thisIndex = int.MaxValue; 

在一個側面說明,您可以通過只使用簡化的方法的其餘部分:

return thisIndex.CompareTo(otherIndex); 
+0

應該是'='而不是'==' – Kami

+0

你是對的,謝謝。 – Servy

+0

找不到item .. otherIndex將爲-1,但返回值將取決於評估'var thisIndex = referenceKeys.IndexOf(thisOne.UId);'。 – Abhijeet