using System;
using System.Collections.Generic;
public class Book : IComparable<Book> {
private string name;
private int circulation;
private class AscendingCirculationComparer : IComparer<Book> {
public int Compare(Book x, Book y) {
if (x == null && y == null) return 0;
else if (x == null) return -1;
else if (y == null) return 1;
if (x == y) return 0;
return x.circulation - y.circulation;
}
}
public Book(string name, int circulation) {
this.name = name;
this.circulation = circulation;
}
public static IComparer<Book> CirculationSorter {
get { return new AscendingCirculationComparer(); }
}
public override string ToString() {
return string.Format("{0}: Circulation = {1}", name, circulation);
}
public int CompareTo(Book other) {
if (other == null) return 1;
if (other == this) return 0;
return string.Compare(this.name, other.name, true);
}
}
public class MainClass {
public static void Main() {
List<Book> Books = new List<Book>();
Books.Add(new Book("E", 1));
Books.Add(new Book("T", 5));
Books.Add(new Book("G", 2));
Books.Add(new Book("S", 8));
Books.Add(new Book("H", 5));
foreach (Book n in Books) {
Console.WriteLine(" " + n);
}
Books.Sort();
foreach (Book n in Books) {
Console.WriteLine(" " + n);
}
Books.Sort(Book.CirculationSorter);
foreach (Book n in Books) {
Console.WriteLine(" " + n);
}
}
}
|