c# - How to correct Generic sort code to sort nullable types -
we've been using method sorting generic list<>. recently, noticed incorrect results when target property in t nullable type (decimal?). ideas how correct?
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 icomparable ? ((icomparable)valuea).compareto(valueb) : 0; }; datasource.sort(compare); }
above code phil hustead's article, "sorting generic lists , ienumerables object property name" http://www.codeproject.com/articles/27851/sorting-generic-lists-and-ienumerables-by-object-p
for instance, employee objects nullable decimal property hours.
the nullable hours 107, null, 8, 152, 64, null sorts 8, null, 64, null, 107, 152.
the nulls should sort, think, beginning or end of list.
change 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 icomparable ? ((icomparable)valuea).compareto(valueb) : 0; }; datasource.sort(compare); }
main issue checking valuea
icomparable
only, , if valuea == null
- comparison returns objects equal, no matter in valueb
. when nullable value boxed (and happening here) represented actual value or null
.
Comments
Post a Comment