2012-05-01 23:59:39|?次阅读|上传:wustguangh【已有?条评论】发表评论
用于进行测试的类ContactInfo:
public class ContactInfo { public ContactInfo() { } public ContactInfo(int id, string name, DateTime date, string subject, double con) { this.id = id; this.name = name; this.date = date; this.subject = subject; this.concentration = con; } private int id; public int Id { get { return id; } set { id = value; } } private string name; public string Name { get { return name; } set { name = value; } } private DateTime date; public DateTime Date { get { return date; } set { date = value; } } private string subject; public string Subject { get { return subject; } set { subject = value; } } private double concentration; public double Concentration { get { return concentration; } set { concentration = value; } } }
此类描述了通信录中的记录,只包含比较简单的方法,在此不详细讨论,然后介绍两个用于排序比较的类:
/// <summary> /// reusable custom DataRow comparer implementation, can be used to sort DataTables /// </summary> public class DataRowComparer : IComparer { ListSortDirection direction; int columnIndex; public DataRowComparer(int columnIndex, ListSortDirection direction) { this.columnIndex = columnIndex; this.direction = direction; } #region IComparer Members public int Compare(object x, object y) { DataRow obj1 = (DataRow)x; DataRow obj2 = (DataRow)y; return string.Compare(obj1[columnIndex].ToString(), obj2[columnIndex].ToString()) * (direction == ListSortDirection.Ascending ? 1 : -1); } #endregion } // custom object comparer implementation public class ContactInfoComparer : IComparer { private int propertyIndex; ListSortDirection direction; public ContactInfoComparer(int propertyIndex, ListSortDirection direction) { this.propertyIndex = propertyIndex; this.direction = direction; } #region IComparer Members public int Compare(object x, object y) { ContactInfo obj1 = (ContactInfo)x; ContactInfo obj2 = (ContactInfo)y; switch (propertyIndex) { case 1: return CompareStrings(obj1.Name, obj2.Name); case 2: return CompareDates(obj1.Date, obj2.Date); case 3: return CompareStrings(obj1.Subject, obj2.Subject); case 4: return CompareNumbers(obj1.Concentration, obj2.Concentration); default: return CompareNumbers((double)obj1.Id, (double)obj2.Id); } } #endregion private int CompareStrings(string val1, string val2) { return string.Compare(val1, val2) * (direction == ListSortDirection.Ascending ? 1 : -1); } private int CompareDates(DateTime val1, DateTime val2) { if (val1 > val2) return (direction == ListSortDirection.Ascending ? 1 : -1); if (val1 < val2) return (direction == ListSortDirection.Ascending ? -1 : 1); return 0; } private int CompareNumbers(double val1, double val2) { if (val1 > val2) return (direction == ListSortDirection.Ascending ? 1 : -1); if (val1 < val2) return (direction == ListSortDirection.Ascending ? -1 : 1); return 0; } }