How to fix common sort code to sort types with null value

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.

+4
source share
2 answers

Change your method to

 public static 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); if(valueA == null) { if(valueB == null) { return 0; } else { return asc ? -1 : 1; } } if(valueB == null) { return asc ? 1 : -1; } return valueA is IComparable ? ((IComparable)valueA).CompareTo(valueB) : 0; }; dataSource.Sort(compare); } 

The main problem is that you only check valueA for valueA only, and if valueA == null - the comparison returns that the objects are equal, regardless of what is in valueB . When the nullable value is turned on (and this is exactly what happens here), it is represented by the actual value or null .

+4
source

The above (final) example supporting NULL values ​​works fine for my list, but only in certain scenarios. My CustomType contains four fields, two of which are string types, and two of them are DateTime? (null) types.

When I sort by any of the string values, it works fine. However, when do I sort any of the null DateTimes? values, does it sort one DateTime? right, but it "loses" information for string values!

Do I have a list sorted by the specified DateTime? value and still contains another DateTime? values ​​but empty string values?

Any ideas here?

0
source

All Articles