2012-11-30 49 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