日期:2014-05-20 浏览次数:20719 次
Person[] people = new Person[]{ new Person(3, "Andy", new DateTime(1982, 10, 3)), new Person(1, "Tom", new DateTime(1993, 2, 10)), new Person(2, "Jerry", new DateTime(1988, 4, 23)) };
class Person { public int Id { get; set; } public string Name { get; set; } public DateTime Birthday { get; set; } public Person(int id, string name, DateTime birthday) { Id = id; Name = name; Birthday = birthday; } public override string ToString() { return String.Format("Id: {0,-6}Name: {1,-20}Birthday: {2:yyyy-MM-dd}", Id, Name, Birthday); } }
public static void Sort<T>( T[] array, Comparison<T> comparison )
static int CompareById(Person first, Person second) { if (first.Id > second.Id) return 1; if (first.Id == second.Id) return 0; return -1; }
Array.Sort(people, new Comparison<Person>(CompareById));
foreach (Person p in people) Console.WriteLine(p);
static int CompareById(Person first, Person second) { return first.Id.CompareTo(second.Id); }
Array.Sort(people, delegate(Person first, Person second){ return first.Id.CompareTo(second.Id); });
Array.Sort(people, (first, second) => first.Id.CompareTo(second.Id));
public static Comparison<Person> CompareByProperty(string name) { switch (name) { case "Id": return (first, second) => first.Id.CompareTo(second.Id); case "Name": return (first, second) => first.Name.CompareTo(second.Name); case "Birthday": return (first, second) => first.Birthday.CompareTo(second.Birthday); default: throw new Exception("属性 " + name + " 不存在。"); } }