We used this method to sort the general list <>. Recently, we noticed incorrect results when the target property in T was a null type (decimal?). Any ideas how to fix it?
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); }
Above is the code from Phil Hastad’s article “Sorting General Lists and IEnumerables by Object Name” http://www.codeproject.com/Articles/27851/Sorting-Generic-Lists-and-IEnumerables-by-Object-P
For example, for my Employee objects with a zero decimal value.
Nominal hours 107, null, 8, 152, 64, null sorts 8, null, 64, null, 107, 152 .
Zeros should sort, I think, at the beginning or at the end of the list.
source share