c# 中 List能对T对象排序的方法(二)

下面的例子能够解释清楚了:
public class Book { private string name; public string Name { get { return name; } set { name = value; } } private int year; public int Year { get { return year; } set { year = value; } } private int price; public int Price { get { return price; } set { price = value; } } public Book(string name,int year, int price) { Name = name; Year = year; Price = price; } } //sort according to the price, default is from small to big public class ComparableBookPriceInc : IComparer<Book> { public int Compare(Book b1, Book b2) { return b1.Price.CompareTo(b2.Price); } } //sort according to year, default is from small to big public class ComparableBookYearInc : IComparer<Book> { public int Compare(Book b1, Book b2) { return b1.Year.CompareTo(b2.Year); } } static void Main(string[] args) { List<Book> listBook = new List<Book>(); Book b1, b2, b3, b4; b1 = new Book("b1", 2006, 100); b2 = new Book("b2", 2007, 50); b3 = new Book("b3", 2008, 200); b4 = new Book("b4", 2009, 70); listBook.Add(b1); listBook.Add(b2); listBook.Add(b3); listBook.Add(b4); Console.WriteLine("Sort by price incremental"); Console.WriteLine("Name/tPrice/tYear/t"); listBook.Sort(new ComparableBookPriceInc()); for (int i = 0; i < listBook.Count;i++ ) { Console.WriteLine(listBook[i].Name + "/t" + listBook[i].Price.ToString() + "/t" + listBook[i].Year.ToString()); } Console.WriteLine("Sort by year incremental"); Console.WriteLine("Name/tPrice/tYear/t"); listBook.Sort(new ComparableBookYearInc()); for (int i = 0; i < listBook.Count; i++) { Console.WriteLine(listBook[i].Name + "/t" + listBook[i].Price.ToString() + "/t" + listBook[i].Year.ToString()); } }

你可能感兴趣的:(list,String,C#,Class)