IList本身沒有Sort()功能,所以可以先把IList轉換爲List,通過List.Sort(比較器)來進行排序。
寫的比 較器:
internal class ListComparer<T> : IComparer<T>
...{
private string propertyName;
public ListComparer(string PropertyName)
...{
propertyName = PropertyName;
}
IComparer Members#region IComparer<T> Members
public int Compare(T x, T y)
...{
PropertyInfo property = typeof(T).GetProperty(propertyName);
//int16
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.ToInt32(property.GetValue(y, null).ToString());
}
return xNumber.CompareTo(yNumber);
}
//int32
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);
}
//double
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);
}
//DateTime
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);
}
return 0;
}
#endregion
}
根據寫的比較器,首先將Ilist轉換爲LIst, 然後通過List.Sort(比較器)進行排序操作
List<ClickNumber> list1 = new List<ClickNumber>();
list1 = (List<ClickNumber>)list;
ListComparer<ClickNumber> listComparer = new ListComparer<ClickNumber>("ClickNum");
list1.Sort(listComparer);
//list1.Reverse();
this.dataGridView1.DataSource = list1;