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,。。。
请高手们给看看哪里不对了。
public int Compare(Employee x, Employee y) { if(x.EmpId == y.EmpId) return 0; else return x.EmpId > y.EmpId?-1:1; }