List排序的两种方法
2016-01-06 15:09
357 查看
方法一:
先定义一个类,并继承Iconparable接口,在类里面对CompareTo方法进行重写。
public class sort_test:IComparable
{
public int Id { get; set; }
public string Name { get; set; }
public int CompareTo(object obj) {
int result;
try
{
sort_test info = obj as sort_test;
//升序排列
if (this.Id > info.Id)
{
result = -1;
}
else if(this.Id < info.Id)
result = 1;
else
result = 0;
return result;
}
catch (Exception ex) { throw new Exception(ex.Message); }
}
}然后引用下面的方法即可
void Start()
{
List<sort_test> infoList = new List<sort_test>();
infoList.Add(new sort_test() { Id = 1, Name = "苍老师" });
infoList.Add(new sort_test() { Id = 3, Name = "小泽老师" });
infoList.Add(new sort_test() { Id = 2, Name = "波多老师" });
infoList.Sort();
foreach (var item in infoList)
{
Log.E("{0}:{1}",item.Id,item.Name);
}
}
方法二:使用匿名委托,sort_test不需要继承Icomparable
void Start()
{
List<sort_test> infoList = new List<sort_test>();
infoList.Add(new sort_test() { Id = 1, Name = "苍老师" });
infoList.Add(new sort_test() { Id = 3, Name = "小泽老师" });
infoList.Add(new sort_test() { Id = 2, Name = "波多老师" });
infoList.Sort(delegate(sort_test x, sort_test y)
{
if(x.Id > y.Id) return -1;
if(x.Id < y.Id) return 1;
return 0;
});
foreach (var item in infoList)
{
Log.E("{0}:{1}",item.Id,item.Name);
}
}
先定义一个类,并继承Iconparable接口,在类里面对CompareTo方法进行重写。
public class sort_test:IComparable
{
public int Id { get; set; }
public string Name { get; set; }
public int CompareTo(object obj) {
int result;
try
{
sort_test info = obj as sort_test;
//升序排列
if (this.Id > info.Id)
{
result = -1;
}
else if(this.Id < info.Id)
result = 1;
else
result = 0;
return result;
}
catch (Exception ex) { throw new Exception(ex.Message); }
}
}然后引用下面的方法即可
void Start()
{
List<sort_test> infoList = new List<sort_test>();
infoList.Add(new sort_test() { Id = 1, Name = "苍老师" });
infoList.Add(new sort_test() { Id = 3, Name = "小泽老师" });
infoList.Add(new sort_test() { Id = 2, Name = "波多老师" });
infoList.Sort();
foreach (var item in infoList)
{
Log.E("{0}:{1}",item.Id,item.Name);
}
}
方法二:使用匿名委托,sort_test不需要继承Icomparable
void Start()
{
List<sort_test> infoList = new List<sort_test>();
infoList.Add(new sort_test() { Id = 1, Name = "苍老师" });
infoList.Add(new sort_test() { Id = 3, Name = "小泽老师" });
infoList.Add(new sort_test() { Id = 2, Name = "波多老师" });
infoList.Sort(delegate(sort_test x, sort_test y)
{
if(x.Id > y.Id) return -1;
if(x.Id < y.Id) return 1;
return 0;
});
foreach (var item in infoList)
{
Log.E("{0}:{1}",item.Id,item.Name);
}
}
相关文章推荐
- android 代码实现控件之间的间距
- [Android]在代码里运行另一个程序的方法
- 肯特·贝克:改变人生的代码整理魔法
- 网页恶意代码的预防
- 高手写的Tracer-Flash代码调试类代码下载
- CSS代码缩写技巧
- 非主流Q-zOne代码代码搜集第1/2页
- CreateWeb.vbs 代码
- Lua中编译执行代码相关的函数详解
- 更有效率的css代码编写第1/3页
- 代码中到底应不应当写注释?
- SQL语言查询基础:连接查询 联合查询 代码
- 论坛头像随机变换代码
- .NET 常用功能和代码小结
- C#实现压缩HTML代码的方法
- asp编程中常用的javascript辅助代码第1/2页
- C#超实用代码段合集
- Javascript代码在页面加载时的执行顺序介绍
- JS实现图片无间断滚动代码汇总
- 我的论坛源代码(二)