首页 新闻 会员 周边

关于c# IComparer的实现

0
悬赏园豆:10 [已解决问题] 解决于 2013-05-16 17:21
static void Main(string[] args)
        {           
            Employee employee = new Employee();
            List<Employee> employeeList = new List<Employee>();
            employeeList.Add(new Employee() { EmpId = "001", EmpName = "Tony" });
            employeeList.Add(new Employee() { EmpId = "002", EmpName = "Mack" });
            employeeList.Add(new Employee() { EmpId = "003", EmpName = "Jon" });
            employeeList.Add(new Employee() { EmpId = "004", EmpName = "Dawei" });
            employeeList.Add(new Employee() { EmpId = "005", EmpName = "Jack" });
            employeeList.Add(new Employee() { EmpId = "006", EmpName = "Abby" });
            employeeList.Add(new Employee() { EmpId = "007", EmpName = "Carrie" });

            List<Employee> toSortList = new List<Employee>();
            toSortList.Add(new Employee() { EmpId = "003", EmpName = "Jon" });
            toSortList.Add(new Employee() { EmpId = "005", EmpName = "Jack" });
            toSortList.Add(new Employee() { EmpId = "007", EmpName = "Carrie" });

            DinoComparer dc = new DinoComparer(toSortList);
            employeeList.Sort(dc);            
        }

        public class DinoComparer : IComparer<Employee>
        {
            List<Employee> toSortList = null;

            public DinoComparer(List<Employee> toSortList)
            {
                this.toSortList = toSortList;
            }

            public int Compare(Employee x, Employee y)
            {
                int ret = toSortList.Count(e => e.EmpId == x.EmpId) > 0 ? -1 : 1;
                return ret;

            }
        }

        public class Employee
        {
            public string EmpId
            {
                get;
                set;
            }

            public string EmpName
            {
                get;
                set;
            }
        }

我想让list里的类,按自定义的顺序排序。上端代码出来的排序顺序是007,001,。。。不是我要的003,005,007,。。。

请高手们给看看哪里不对了。

托雷的主页 托雷 | 初学一级 | 园豆:184
提问于:2013-05-16 16:55
< >
分享
最佳答案
0
 public int Compare(Employee x, Employee y)
{
       if(x.EmpId == y.EmpId)
             return 0;
      else
             return x.EmpId > y.EmpId?-1:1;
}
收获园豆:10
滴答的雨 | 老鸟四级 |园豆:3660 | 2013-05-16 17:05
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册