zoukankan      html  css  js  c++  java
  • c# list排序的三种实现方式

    c# list排序的三种实现方式

     

    用了一段时间的gridview,对gridview实现的排序功能比较好奇,而且利用C#自带的排序方法只能对某一个字段进行排序,今天demo了一下,总结了三种对list排序的方法,并实现动态传递字段名对list进行排序。

    首先先介绍一下平时最常用的几种排序方法。

    第一种:实体类实现IComparable接口,而且必须实现CompareTo方法

    实体类定义如下:

    View Code
    1 class Info:IComparable
     2     {
     3         public int Id { get; set; }
     4         public string Name { get; set; }
     5 
     6         public int CompareTo(object obj) {
     7             int result;
     8             try
     9             {
    10                 Info info = obj as Info;
    11                 if (this.Id > info.Id)
    12                 {
    13                     result = 0;
    14                 }
    15                 else
    16                     result = 1;
    17                 return result;
    18             }
    19             catch (Exception ex) { throw new Exception(ex.Message); }
    20         }
    21     }
    复制代码
     1 class Info:IComparable
     2     {
     3         public int Id { get; set; }
     4         public string Name { get; set; }
     5 
     6         public int CompareTo(object obj) {
     7             int result;
     8             try
     9             {
    10                 Info info = obj as Info;
    11                 if (this.Id > info.Id)
    12                 {
    13                     result = 0;
    14                 }
    15                 else
    16                     result = 1;
    17                 return result;
    18             }
    19             catch (Exception ex) { throw new Exception(ex.Message); }
    20         }
    21     }
    复制代码

    调用方式如下,只需要用sort方法就能实现对list进行排序。

    View Code
    1 private static void ReadAccordingCompare() {
     2             List<Info> infoList = new List<Info>();
     3             infoList.Add(
     4                 new Info() { Id = 1, Name = "abc" });
     5             infoList.Add(new Info() { Id = 3, Name = "rose" });
     6             infoList.Add(new Info() { Id = 2, Name = "woft" });
     7                infoList.Sort();
     8             foreach (var item in infoList)
     9             {
    10                 Console.WriteLine(item.Id + ":" + item.Name); 
    11             }
    12         }
    复制代码
     1 private static void ReadAccordingCompare() {
     2             List<Info> infoList = new List<Info>();
     3             infoList.Add(
     4                 new Info() { Id = 1, Name = "abc" });
     5             infoList.Add(new Info() { Id = 3, Name = "rose" });
     6             infoList.Add(new Info() { Id = 2, Name = "woft" });
     7                infoList.Sort();
     8             foreach (var item in infoList)
     9             {
    10                 Console.WriteLine(item.Id + ":" + item.Name); 
    11             }
    12         }
    复制代码

    第二种方法:linq to list进行排序

    运用linq实现对list排序,在实体类定义的时候就不需用实现IComparable接口,调用方式如下:

    View Code
    1 private static void ReadT(string str) {
     2             List<Info> infoList = new List<Info>();
     3             infoList.Add(
     4                 new Info() { Id = 1, Name = "woft" });
     5             infoList.Add(new Info() { Id=3,Name="rose"});
     6             infoList.Add(new Info() { Id = 2, Name = "abc" });
     7             Console.WriteLine("ReadT*********************");
     8             IEnumerable<Info> query = null;
     9             query = from items in infoList orderby items.Id select items;
    10             foreach (var item in query)
    11             {
    12                 Console.WriteLine(item.Id+":"+item.Name);
    13             }
    14         }
    复制代码
     1 private static void ReadT(string str) {
     2             List<Info> infoList = new List<Info>();
     3             infoList.Add(
     4                 new Info() { Id = 1, Name = "woft" });
     5             infoList.Add(new Info() { Id=3,Name="rose"});
     6             infoList.Add(new Info() { Id = 2, Name = "abc" });
     7             Console.WriteLine("ReadT*********************");
     8             IEnumerable<Info> query = null;
     9             query = from items in infoList orderby items.Id select items;
    10             foreach (var item in query)
    11             {
    12                 Console.WriteLine(item.Id+":"+item.Name);
    13             }
    14         }
    复制代码

    但是上面两种方式都只能对一个实体属性排序,如果对不同的属性排序的话只能写很多的if进行判断,这样显得很麻烦。

    且看下面的方式实现根据传入参数进行排序。

    View Code
    1 private static void ListSort(string field,string rule)
     2         {
     3             if (!string.IsNullOrEmpty(rule)&&(!rule.ToLower().Equals("desc")||!rule.ToLower().Equals("asc")))
     4             {
     5                 try
     6                 {
     7                     List<Info> infoList = GetList();
     8                     infoList.Sort(
     9                         delegate(Info info1, Info info2)
    10                         {
    11                             Type t1 = info1.GetType();
    12                             Type t2 = info2.GetType();
    13                             PropertyInfo pro1 = t1.GetProperty(field);
    14                             PropertyInfo pro2 = t2.GetProperty(field);
    15                             return rule.ToLower().Equals("asc") ?
    16                                 pro1.GetValue(info1, null).ToString().CompareTo(pro2.GetValue(info2, null).ToString()) :
    17                                 pro2.GetValue(info2, null).ToString().CompareTo(pro1.GetValue(info1, null).ToString());
    18                         });
    19                     Console.WriteLine("*****ListSort**********");
    20                     foreach (var item in infoList)
    21                     {
    22                         Console.WriteLine(item.Id + "," + item.Name);
    23                     }
    24                 }
    25                 catch (Exception ex)
    26                 {
    27                     Console.WriteLine(ex.Message);
    28                 }
    29             } Console.WriteLine("ruls is wrong");
    30 
    31         }
    复制代码
     1 private static void ListSort(string field,string rule)
     2         {
     3             if (!string.IsNullOrEmpty(rule)&&(!rule.ToLower().Equals("desc")||!rule.ToLower().Equals("asc")))
     4             {
     5                 try
     6                 {
     7                     List<Info> infoList = GetList();
     8                     infoList.Sort(
     9                         delegate(Info info1, Info info2)
    10                         {
    11                             Type t1 = info1.GetType();
    12                             Type t2 = info2.GetType();
    13                             PropertyInfo pro1 = t1.GetProperty(field);
    14                             PropertyInfo pro2 = t2.GetProperty(field);
    15                             return rule.ToLower().Equals("asc") ?
    16                                 pro1.GetValue(info1, null).ToString().CompareTo(pro2.GetValue(info2, null).ToString()) :
    17                                 pro2.GetValue(info2, null).ToString().CompareTo(pro1.GetValue(info1, null).ToString());
    18                         });
    19                     Console.WriteLine("*****ListSort**********");
    20                     foreach (var item in infoList)
    21                     {
    22                         Console.WriteLine(item.Id + "," + item.Name);
    23                     }
    24                 }
    25                 catch (Exception ex)
    26                 {
    27                     Console.WriteLine(ex.Message);
    28                 }
    29             } Console.WriteLine("ruls is wrong");
    30 
    31         }
    复制代码

    调用方式:

    ListSort("Name","desc");//表示对Name进行desc排序
    ListSort("Id","asc");//表示对Id进行asc排序。如此如果参数很多的话减少了很多判断。

    如果有更好的方法欢迎提出,共同学习………..

     
    分类: asp.net
  • 相关阅读:
    split 使用
    python中接受上一条命令执行的结果----subprocess.check_output()
    k8s开启cadvisor http 服务
    Spring Cloud之配置中心搭建
    如何高效地学习开源项目
    Spring Boot之默认连接池配置策略
    Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: ..... this is incompatible with sql_mode=only_full_group_by
    com.netflix.zuul.exception.ZuulException: Forwarding error
    设置环境变量相关命令
    java.lang.NoClassDefFoundError: org/springframework/web/context/WebApplicationContext
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/2554946.html
Copyright © 2011-2022 走看看