protected void btnSort_Click(object sender, EventArgs e)
{
List<Book> list = new List<Book>();
Book b1, b2, b3, b4;
b1 = new Book("《绝代双骄》", "古龙", "中国长安出版社", 50);
b2 = new Book("《鹿鼎记》", "金庸", "人民文学出版社", 120);
b3 = new Book("《三国演义》", "罗贯中", "中州古籍出版社", 200);
b4 = new Book("《西游记》", "吴承恩", "晨光出版社", 80);
list.Add(b1);
list.Add(b2);
list.Add(b3);
list.Add(b4);
//按书名升序
Response.Write("/按书名升序/<br />");
list.Sort(new Icp());
foreach (Book book in list)
{
Response.Write(book.Name + book.Author + book.Publi
sher + book.Price + "<br />");
}
Response.Write("<br />");
//按价格降序序
Response.Write("/按价格升序/<br />");
list.Sort(new IcpPrice());
foreach (Book book in list)
{
Response.Write(book.Name + book.Author + book.Publisher + book.Price + "<br />");
}
}
==============================================================
public class Book
{
public Book(string inname, string inauthor, string inpublisher, int inprice)
{
this.Name = inname;
this.Author = inauthor;
this.Publisher = inpublisher;
this.Price = inprice;
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private string author;
public string Author
{
get { return author; }
set { author = value; }
}
private string publisher;
public string Publisher
{
get { return publisher; }
set { publisher = value; }
}
private int price;
public int Price
{
get { return price; }
set { price = value; }
}
}
//比较器类
public class Icp : IComparer<Book>
{
//按书名排序
public int Compare(Book x, Book y)
{
return x.Name.CompareTo(y.Name);
}
}
public class IcpPrice : IComparer<Book>
{
//按价格排序
public int Compare(Book x, Book y)
{
return x.Price.CompareTo(y.Price);
}
}
==============================================================
public class Book
{
}
//比较器类
public class Icp : IComparer<Book>
{
}
public class IcpPrice : IComparer<Book>
{
}