用了一段时间的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. 供应商API补充(详解EBS接口开发之供应商导入)(转)

    原文地址  供应商导入的API补充(详解EBS接口开发之供应商导入) --供应商 --创建 AP_VENDOR_PUB_PKG.Create_Vendor ( p_api_version IN NUM ...

  2. 获取Oracle数据库awr报告方法

    --登录数据库  sqlplus username/passwd; --运行生成AWR报告脚本  SQL> @?/rdbms/admin/awrrpt.sql; --输入要生成报告的格式:htm ...

  3. win10启动移动热点解决办法

    netsh wlan start hostednetwork C:\Windows\System32\GroupPolicy\Machine\Scripts\Startup gpedit.msc

  4. springboot2.0 web 开发标准目录架构

    ├── clean-run.sh ├── logs/ 日志文件目录 │ ├── sb2-web_test_2018-06-02_0959.0.log │ └── sb2-web_test.log | ...

  5. STL标准库-算法-常用算法

    技术在于交流.沟通,本文为博主原创文章转载请注明出处并保持作品的完整性 介绍11种STL标准库的算法,从这11种算法中总结一下算法的基本使用 1.accumulate() 累加 2.for_each( ...

  6. 一起来点React Native——常用组件之Touchable系列

    在前面的登录界面中,我们发现所有的组件不会对用户的点击.触摸.拖拽做出合适的响应,这是十分不友好的.那么,在React Native中如何让视图对触发做出合适的响应呢? 一.高亮触摸  Touchab ...

  7. MVA Prototype Only User License

    This App is only a protetype of MVA WP app, the intent is to demostrate to Leadership person about w ...

  8. scanf格式化中的\n

    如果一个scanf的格式串以\n结尾,那么在读取完后还会阻塞等待,比如: int a; scanf("%d\n", &a); 这种情况,输入一个数字然后敲下回车后,程序还是 ...

  9. 通过JS动态创建和删除HTML元素

    <script type="text/javascript" language="Javascript"> function InputOnBlur ...

  10. caffe安装编译问题-ImportError: No module named skimage.io

    问题描述 >>> import caffe Traceback (most recent call last): File , in <module> File , in ...