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

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

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

实体类定义如下:

按 Ctrl+C 复制代码

class Info:IComparable
{
public int Id { get; set; }
public string Name { get; set; }

public int CompareTo(object obj) {
int result;
try
{
Info info = obj as Info;
if (this.Id > info.Id)
{
result = 0;
}
else
result = 1;
return result;
}
catch (Exception ex) { throw new Exception(ex.Message); }
}
}

按 Ctrl+C 复制代码

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

 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接口,调用方式如下:

 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进行判断,这样显得很麻烦。

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

 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排序。如此如果参数很多的话减少了很多判断。

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

后续:受一位留言着的提醒,在用反射实现多字段排序时只需一次反射,多余的一次放而会影响性能,现更新如下:

 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 t = typeof(Info);
12 PropertyInfo pro = t.GetProperty(field);
13 return rule.ToLower().Equals("asc") ?
14 pro.GetValue(info1, null).ToString().CompareTo(pro.GetValue(info2, null).ToString()) :
15 pro.GetValue(info2, null).ToString().CompareTo(pro.GetValue(info1, null).ToString());
16 });
17 Console.WriteLine("*****ListSort**********");
18 foreach (var item in infoList)
19 {
20 Console.WriteLine(item.Id + "," + item.Name);
21 }
22 }
23 catch (Exception ex)
24 {
25 Console.WriteLine(ex.Message);
26 }
27 }
28 else
29 Console.WriteLine("ruls is wrong");
30 }
 

c# list排序的三种实现方式 (转帖)的更多相关文章

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

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

  2. Linq to Sql : 三种事务处理方式

    原文:Linq to Sql : 三种事务处理方式 Linq to SQL支持三种事务处理模型:显式本地事务.显式可分发事务.隐式事务.(from  MSDN: 事务 (LINQ to SQL)).M ...

  3. EF三种编程方式图文详解

    Entity Framework4.1之前EF支持“Database First”和“Model First”编程方式,从EF4.1开始EF开始支持支持“Code First”编程方式,今天简单看一下 ...

  4. 数组的三种声明方式总结、多维数组的遍历、Arrays类的常用方法总结

    1. 数组的三种声明方式 public class WhatEver { public static void main(String[] args) { //第一种 例: String[] test ...

  5. EF三种编程方式详细图文教程(C#+EF)之Database First

    Entity Framework4.1之前EF支持“Database First”和“Model First”编程方式,从EF4.1开始EF开始支持支持“Code First”编程方式,今天简单看一下 ...

  6. oracle Hash Join及三种连接方式

    在Oracle中,确定连接操作类型是执行计划生成的重要方面.各种连接操作类型代表着不同的连接操作算法,不同的连接操作类型也适应于不同的数据量和数据分布情况. 无论是Nest Loop Join(嵌套循 ...

  7. Hive的三种Join方式

    Hive的三种Join方式 hive Hive中就是把Map,Reduce的Join拿过来,通过SQL来表示. 参考链接:https://cwiki.apache.org/confluence/dis ...

  8. python笔记-20 django进阶 (model与form、modelform对比,三种ajax方式的对比,随机验证码,kindeditor)

    一.model深入 1.model的功能 1.1 创建数据库表 1.2 操作数据库表 1.3 数据库的增删改查操作 2.创建数据库表的单表操作 2.1 定义表对象 class xxx(models.M ...

  9. SQL Server中的三种Join方式

      1.测试数据准备 参考:Sql Server中的表访问方式Table Scan, Index Scan, Index Seek 这篇博客中的实验数据准备.这两篇博客使用了相同的实验数据. 2.SQ ...

随机推荐

  1. OAF 交互式列车 上一步 下一步的简单使用

    在实际的需求中,我们往往会遇到在下一步的时候验证某些参数,而上一步不需要验证. 这个是非常粗暴的解决方式 if( "goto".equals(pageContext.getPara ...

  2. oracle EBS grant 您不具有执行当前操作的足够权限。请与您的系统管理员联系。

    解决方式1: Set the profiles of the below three to 'None' 设置以下三个配置文件为无 FND_VALIDATION_LEVELFND 验证层 FND_FU ...

  3. vue2.0对不同数据类型的显示

  4. 等待进程结束wait,waitpid

    当子进程先于父进程退出时,如果父进程没有调用wait和waitpid函数,子进程就会进入僵死状态. pid_t wait(int *status); pid_t waitpid(pid_t pid, ...

  5. Filesystem has been set read-only problem.

    case: when system is running well ,sudden tf became read-only; analyze: read the kernel log using dm ...

  6. learning armbian steps(2) ----- armbian 镜像编译

    参考:https://docs.armbian.com/Developer-Guide_Build-Preparation/ 通过如下指令进行编译: apt-get -y -qq install gi ...

  7. 参数 out

    function outtest(out jo: ISuperObject; out s: string):Boolean; begin //进入函数时 jo =nil ErrStr = '' Res ...

  8. EXCEL FAQ

    1.win7双击打开EXCEL07时显示停止工作,但是在打开方式中可以打开,怎么破? 加载项的问题,在选项-信任中心-信任中心设置-加载项-禁用所有应用程序加载项即可,但是这样会丧失一些功能,也可以把 ...

  9. 2019.1.7 Russia temperature control demo

    1layout 2导出Gerber 做钢网 3刷锡膏 4.1调SMT程序: a摆元件,写P/N位置 b定位检测点 4.2手贴元件 手别抖! 5过炉 温度270 6插件PCBA 做载板最方便,手插焊接也 ...

  10. 深入理解uwsgi和gunicorn网络模型

    前言: 去年10月份建了一个python技术群,到现在为止人数已经涨到700人了.最一开始我经常在群里回应大家的问题,不管是简单还是困难的,我都会根据自己的经验来交流. 让人新奇的是一些初学者关注最多 ...