class Entity { public Entity() {} privateint id; publicint Id { get { return id; } set { id = value; } } privatestring name; publicstring Name { get { return name; } set { name = value; } } privatedouble price; publicdouble Price { get { return price; } set { price = value; } } }
然后写一个对象比较的类,实现IComparer<T>接口。
internalclass ListComparer<TBaseBusinessObject> : IComparer<TBaseBusinessObject> { privatestring propertyName; public ListComparer(string PropertyName) { propertyName = PropertyName; } IComparer
Members#region IComparer<TBaseBusinessObject> Members publicint Compare(TBaseBusinessObject x, TBaseBusinessObject y) { PropertyInfo property =typeof(TBaseBusinessObject).GetProperty(propertyName); if (property.PropertyType == Type.GetType("System.Int16")) { int xNumber =0; int yNumber =0; if (property.GetValue(x, null) !=null) { xNumber = Convert.ToInt16(property.GetValue(x, null).ToString()); } if (property.GetValue(y, null) !=null) { yNumber = Convert.ToInt16(property.GetValue(y, null).ToString()); } return xNumber.CompareTo(yNumber); } if (property.PropertyType == Type.GetType("System.Int32")) { int xNumber =0; int yNumber =0; if (property.GetValue(x, null) !=null) { xNumber = Convert.ToInt32(property.GetValue(x, null).ToString()); } if (property.GetValue(y, null) !=null) { yNumber = Convert.ToInt32(property.GetValue(y, null).ToString()); } return xNumber.CompareTo(yNumber); } if (property.PropertyType == Type.GetType("System.Double")) { double xNumber =0; double yNumber =0; if (property.GetValue(x, null) !=null) { xNumber = Convert.ToDouble(property.GetValue(x, null).ToString()); } if (property.GetValue(y, null) !=null) { yNumber = Convert.ToDouble(property.GetValue(y, null).ToString()); } return xNumber.CompareTo(yNumber); } if (property.PropertyType == Type.GetType("System.DateTime")) { DateTime xTime = DateTime.Now; DateTime yTime = DateTime.Now; if (property.GetValue(x, null) !=null) { xTime = Convert.ToDateTime(property.GetValue(x, null).ToString()); } if (property.GetValue(y, null) !=null) { yTime = Convert.ToDateTime(property.GetValue(y, null).ToString()); } return xTime.CompareTo(yTime); } if ((property.PropertyType == Type.GetType("System.String")) || (property.PropertyType == Type.GetType("System.Boolean"))) { string xText =string.Empty; string yText =string.Empty; if (property.GetValue(x, null) !=null) { xText = property.GetValue(x, null).ToString(); } if (property.GetValue(y, null) !=null) { yText = property.GetValue(y, null).ToString(); } return xText.CompareTo(yText); } return0; } #endregion }