欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

list泛型自定义排序示例

程序员文章站 2024-02-27 17:55:57
复制代码 代码如下:static void main(string[] args){    employee employee = new e...

复制代码 代码如下:

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" });
    //自定义 排序委托
    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;
    }
}

经过排序后将原本list中按001,002,003,排列的元素排序为003,005,007,001,002,004.。。。将指定的003,005,007,排列在list最前