用了一段时间的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. IOS8-人机界面指南

    [ISUX转译]iOS 8人机界面指南(一):UI设计基础 糖箔糊2014.09.23 文章索引 1.1 为iOS而设计(Designing for iOS) 1.1.1 以内容为核心(Defer t ...

  2. learning shell get script absolute path (3)

    Shell get script absolute path [Purpose]        Get shell script absolute path   [Eevironment]       ...

  3. sgu 129 Inheritance 凸包,线段交点,计算几何 难度:2

    129. Inheritance time limit per test: 0.25 sec. memory limit per test: 4096 KB The old King decided ...

  4. MinGW安装教程——著名C/C++编译器GCC的Windows版本

    前言本文主要讲述如何安装 C语言 编译器——MinGW,特点是文章附有完整详细的实际安装过程截图,文字反而起说明提示作用. 编写本文的原因始于我的一个观点:图片可以比文字传达更多的信息,也能让其他人更 ...

  5. 51nod1837

    题解: 数论,经过一些大佬的证明,只有1和2这两种可能性 然后再分开来判断即可 注意1的时候为0 代码: #include<bits/stdc++.h> using namespace s ...

  6. L1-036 A乘以B

    看我没骗你吧 —— 这是一道你可以在 10 秒内完成的题:给定两个绝对值不超过 100 的整数 A 和 B,输出 A 乘以 B 的值. 输入格式: 输入在第一行给出两个整数 A 和 B(−100≤A, ...

  7. MyEclipse WebSphere开发教程:安装和更新WebSphere 6.1, JAX-WS, EJB 3.0(五)

    MyEclipse超值折扣 限量 100 套! 立即开抢>> [MyEclipse最新版下载] MyEclipse支持Java EE技术(如JAX-WS和EJB 3.0),它们以功能包的形 ...

  8. 注解配置定时任务——@Scheduled

    Java中注解@Scheduled 的注解代码如下: @Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) @Retention(Ret ...

  9. influx+grafana自定义python采集数据和一些坑的总结

    先上网卡数据采集脚本,这个基本上是最大的坑,因为一些数据的类型不正确会导致no datapoint的错误,真是令人抓狂,注意其中几个key的值必须是int或者float类型,如果你不慎写成了strin ...

  10. QLabel 内容长度超过控件本身长度时超出的部分用省略号

    void JunEditableLabel::setText(const QString &string) { QFont font("Tahoma"); font.set ...