您的位置:首页 > 编程语言 > C#

c# list排序的三种实现方式 (转帖)

2014-12-16 09:08 609 查看
用了一段时间的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进行排序。

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 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         }


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: