欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

探讨:如何使用委托,匿名方法对集合进行万能排序

时间:2022-02-15 11:08:00|栏目:.NET代码|点击:
下面Demo中我使用了2种排序方式
1.让Employee继承IComparable 接口,实现CompareTo方法排序
2.定义一个方法使用Comparison<T>委托,排序的操作交给匿名方法
看完下面的代码,你知道使用Comparison<T>委托的好处吗?
复制代码 代码如下:

    class Employee:IComparable
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public static List<Employee> GetEmployees()
        {
            return new List<Employee>()
            {
                new Employee(){Name ="GuoHu",Age =25},
                new Employee(){Name ="LeiHu",Age =23},
                new Employee(){Name ="JunWenLi",Age =24},
                new Employee(){Name ="JinHaoLiu",Age =25},
                new Employee(){Name ="ChengFang",Age =24}
            };
        }
        public int CompareTo(object obj)
        {
            Employee employee = obj as Employee;
            if (employee != null)
            {
                return Name.CompareTo(employee.Name);
            }
            else
            {
                throw new ArgumentException("obj is not Employee");
            }
        }
    }
    class Test
    {
        static void SortAndShowFiles(string title, Comparison<Employee> employeeInfo)
        {
            List<Employee> employee = Employee.GetEmployees();
            employee.Sort(employeeInfo);
            Console.WriteLine(title);
            foreach(Employee e in employee)
            {
                Console.WriteLine("Name:{0},Age:{1}", e.Name, e.Age);
            }
        }
        static void Main()
        {
            List<Employee> employeeInfo = Employee.GetEmployees();
            //Using IComparable sort
            employeeInfo.Sort();
            employeeInfo.ForEach(e => Console.WriteLine("Name:{0},Age{1}/t", e.Name, e.Age));
            SortAndShowFiles("Sort by name", delegate(Employee e1, Employee e2) { return e1.Name.CompareTo(e2.Name); });
            SortAndShowFiles("Sort by age", delegate(Employee e1, Employee e2) { return e1.Age.CompareTo(e2.Age); });
        }

    }

上一篇:asp.net Cookie操作类

栏    目:.NET代码

下一篇:Winform中GridView分组排序功能实现方法

本文标题:探讨:如何使用委托,匿名方法对集合进行万能排序

本文地址:http://www.codeinn.net/misctech/193440.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有