代码
public class Post : IComparable<Post>
{
private string id = string.Empty;
private string title = string.Empty;
private int orderby;
public string ID
{
get
{
return id;
}
set
{
id = value;
}
}
public string Title
{
get
{
return title;
}
set
{
title = value;
}
}
public int OrderBy
{
get
{
return orderby;
}
set
{
orderby = value;
}
}
#region IComparable<Post> 成员
public int CompareTo(Post other)
{
return ( orderby- other.orderby);
}
#endregion
}
{
private string id = string.Empty;
private string title = string.Empty;
private int orderby;
public string ID
{
get
{
return id;
}
set
{
id = value;
}
}
public string Title
{
get
{
return title;
}
set
{
title = value;
}
}
public int OrderBy
{
get
{
return orderby;
}
set
{
orderby = value;
}
}
#region IComparable<Post> 成员
public int CompareTo(Post other)
{
return ( orderby- other.orderby);
}
#endregion
}
让类继承IComparable接口,并且实现接口,在实现接口方法中设置为顺序排序
#region IComparable<Post> 成员
public int CompareTo(Post other)
{
return ( orderby- other.orderby);
}
#endregion
public int CompareTo(Post other)
{
return ( orderby- other.orderby);
}
#endregion
倒序可以设置为
#region IComparable<Post> 成员
public int CompareTo(Post other)
{
return ( other.orderby- orderby);
}
#endregion
public int CompareTo(Post other)
{
return ( other.orderby- orderby);
}
#endregion
默认实现泛型类型排序可以是使用List<T>.Sort()比如
代码
List<Post> posts = new List<Post>();
for (int i = 0; i < 10; i++)
{
Post post = new Post();
post.ID = i.ToString();
post.Title = "哈哈";
post.OrderBy = i;
posts.Add(post);
}
//排序
posts.Sort();
foreach (Post p in posts)
{
Response.Write(p.ID + "<br>");
}
for (int i = 0; i < 10; i++)
{
Post post = new Post();
post.ID = i.ToString();
post.Title = "哈哈";
post.OrderBy = i;
posts.Add(post);
}
//排序
posts.Sort();
foreach (Post p in posts)
{
Response.Write(p.ID + "<br>");
}
我们可以看到输出的结果
0
1
.
.
.
10
如果我们其它属性排序比如ID,TITLE则如何实现?
代码
List<Post> posts = new List<Post>();
for (int i = 0; i < 10; i++)
{
Post post = new Post();
post.ID = i.ToString();
post.Title = "哈哈";
post.OrderBy = i;
posts.Add(post);
}
//排序
//posts.Sort();
posts.Sort(delegate(Post p1, Post p2)
{
return p2.ID.CompareTo(p1.ID);
}
);
foreach (Post p in posts)
{
Response.Write(p.ID + "<br>");
}
for (int i = 0; i < 10; i++)
{
Post post = new Post();
post.ID = i.ToString();
post.Title = "哈哈";
post.OrderBy = i;
posts.Add(post);
}
//排序
//posts.Sort();
posts.Sort(delegate(Post p1, Post p2)
{
return p2.ID.CompareTo(p1.ID);
}
);
foreach (Post p in posts)
{
Response.Write(p.ID + "<br>");
}