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
首先先介绍一下平时最常用的几种排序方法。
第一种:实体类实现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 }
相关文章推荐
- c# list排序的三种实现方式
- c# list排序的三种实现方式
- c# list排序的三种实现方式
- c# list排序的三种实现方式
- c# list排序的三种实现方式
- c# list排序的三种实现方式
- c# list排序的三种实现方式
- list排序的三种实现方式
- c# list排序的实现方式
- list排序的三种实现方式
- 最简单的对Java List列表按中文拼音排序的实现方式
- C#三种WCF网络客户端的实现方式
- Repeater排序的三种实现方式
- C# 三种实现抖屏的方式
- java 实现List对象中按某种方式进行排序
- C#实现面向对象多态性的三种方式
- C#三种方式实现序列化(转)
- C#通过IComparable实现ListT.sort()排序
- C#三种WCF网络客户端的实现方式
- 最简单的对Java List列表按中文拼音排序的实现方式