一般的な List<> をソートするためにこのメソッドを使用してきました。最近、T のターゲット プロパティが null 許容型 (10 進数?) の場合に誤った結果が生じることに気付きました。修正方法はありますか?
public void SortList<T>(List<T> dataSource, string fieldName, SortDirection sortDirection)
{
PropertyInfo propInfo = typeof(T).GetProperty(fieldName);
Comparison<T> compare = delegate(T a, T b)
{
bool asc = sortDirection == SortDirection.Ascending;
object valueA = asc ? propInfo.GetValue(a, null) : propInfo.GetValue(b, null);
object valueB = asc ? propInfo.GetValue(b, null) : propInfo.GetValue(a, null);
return valueA is IComparable ? ((IComparable)valueA).CompareTo(valueB) : 0;
};
dataSource.Sort(compare);
}
上記の Phil Hustead の記事「Sorting Generic Lists and IEnumerables by Object Property Name」のコード http://www.codeproject.com/Articles/27851/Sorting-Generic-Lists-and-IEnumerables-by-Object-P
たとえば、null 許容の decimal プロパティHoursを持つEmployeeオブジェクトの場合。
null 許容時間 107, null, 8, 152, 64, nullは8, null, 64, null, 107, 152 に ソートされ ます。
ヌルは、リストの先頭または末尾にソートする必要があると思います。