基于预定义键的自定义排序

时间:2012-11-30 16:10:28

标签: c# sorting

我需要根据预定义的uniqueIds对员工列表进行排序。

简单来说,请考虑员工ID 1 to 10 in random order.

列表

我有一个预定义的规则,说明2, 8, 1, 4, 6中的员工对象,如果任何员工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();
        }
    }

我已经能够对列表进行排序,结果如下 -

(5, 7, 3), 2, 8, 1, 4, 6 ==&gt; 5,7,3未列在参考键中,因此应该出现在最后,任何顺序..

但是我的参考键中找不到的项目会先排序。我需要把它们放在最后。

对于这种情况,IComparer是最好的方法吗?

1 个答案:

答案 0 :(得分:4)

如果找不到该项,

var otherIndex = referenceKeys.IndexOf(otherOne.UId);将返回-1,该项将小于找到的任何值。

您希望所有未找到的项目都大于任何找到的值,因此只需添加:

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

另外,您可以通过以下方式简化方法的其余部分:

return thisIndex.CompareTo(otherIndex);