Example of list generic custom sorting

  • 2020-11-25 07:12:43
  • OfStack


static void Main(string[] args)
{

    Employee employee = new Employee();
    // Set the initial value 
    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" });
    // Specifies the presorted elements 
    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" });
    // The custom   Commissioned by sorting 
    employeeList.Sort((Employee x, Employee y) => (toSortList.Count(e => e.EmpId == y.EmpId) - toSortList.Count(e => e.EmpId == x.EmpId)));
}

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

    public string EmpName
    {
        get;
        set;
    }
}

After sorting, the elements in the original list sorted by 001,002,003 are sorted as 003,005,007,001,002,004... Place the specified number 003,005,007 at the top of List


Related articles: