用了一段时间的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. C# / .NET 在类中使用Server.MapPath

    直接在类中使用 Server.MapPath 会出现错误,这是由于类中不能直接使用 System.Web.UI.Page 的非静态函数造成的.解决方法有两种: 方法一.使类继承System.Web.U ...

  2. POJ 2663 Tri Tiling 矩阵快速幂 难度:3

    Tri Tiling Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 7841   Accepted: 4113 Descri ...

  3. Flash网页mp3播放器代码(3例)

    第一款:可以添加多首歌 代码如下:可以添加多首歌曲中间用 |  间隔符号隔开 <EMBED  height=20 type=application/x-shockwave-flash plugi ...

  4. 【转】个人总结-网络安全学习和CTF必不可少的一些网站

    转自:http://blog.csdn.net/ida0918/article/details/52730662 学习的地方很多,不能一一列举,一些优秀的网址和博客可能也没有提到,大家补充吧:P就简单 ...

  5. python 的StringIO

    python 3.4以后StringIO和cStringIO就没有了,转移到 io,的StringIO和BytesIO from io import StringIO fp=StringIO( ) 1 ...

  6. 2019.1.5 China’s population

    China’s population is expected to hit a peak of 1.44 billion in 2029, and start to experience negati ...

  7. the usage of String

    经典算法:(整理汇总) 1)如何快速倒叙: public static char[] reverseArray(char[] c){ char t; for(int i=0;i<c.length ...

  8. makefile的一个错误:*** missing separator

    原文转自:http://blog.sina.com.cn/s/blog_87c063060101c9yp.html 1.在写 多目录下makefile的时候,碰到一个错误提示,让我纠结许久,后面还是解 ...

  9. B - Build The Electric System 求强连通的最小和//lxm

    有n个城市,有m条线路,每条线路a,b,len表示a到b的线路需要花费len的费用维修,要求能将所有城市联通的最小维修花费 按照排序排一下然后利用并查集解决 #include <iostream ...

  10. py安装以及配置pip环境变量

    安装python,安装包链接:https://pan.baidu.com/s/1u4tA-FJMxtrtJTap-zFh3g 密码:gh1c 默然安装到了C盘 安装pycharm:安装包链接:链接:h ...