实现List泛型类将制定元素至前排序
1 static void Main(string[] args) 2 { 3 4 Employee employee = new Employee(); 5 //设置初始值 6 List<Employee> employeeList = new List<Employee>(); 7 employeeList.Add(new Employee() { EmpId = "001", EmpName = "Tony" }); 8 employeeList.Add(new Employee() { EmpId = "002", EmpName = "Mack" }); 9 employeeList.Add(new Employee() { EmpId = "003", EmpName = "Jon" }); 10 employeeList.Add(new Employee() { EmpId = "004", EmpName = "Dawei" }); 11 employeeList.Add(new Employee() { EmpId = "005", EmpName = "Jack" }); 12 employeeList.Add(new Employee() { EmpId = "006", EmpName = "Abby" }); 13 employeeList.Add(new Employee() { EmpId = "007", EmpName = "Carrie" }); 14 //指定置前排序元素 15 List<Employee> toSortList = new List<Employee>(); 16 toSortList.Add(new Employee() { EmpId = "003", EmpName = "Jon" }); 17 toSortList.Add(new Employee() { EmpId = "005", EmpName = "Jack" }); 18 toSortList.Add(new Employee() { EmpId = "007", EmpName = "Carrie" }); 19 //自定义 排序委托 20 employeeList.Sort((Employee x, Employee y) => (toSortList.Count(e => e.EmpId == y.EmpId) - toSortList.Count(e => e.EmpId == x.EmpId))); 21 } 22 23 public class Employee 24 { 25 public string EmpId 26 { 27 get; 28 set; 29 } 30 31 public string EmpName 32 { 33 get; 34 set; 35 } 36 }
经过排序后将原本list中按001,002,003,排列的元素排序为003,005,007,001,002,004.。。。将指定的003,005,007,排列在List最前