c# - How to sort a List, by any of its properties? -
c# - How to sort a List<T>, by any of its properties? -
i'm trying sort list<t>
, without using orderby
, orderbydescending
, t
custom class. code:
class { public string category { get; set; } public int fingers { get; set; } public datetime creation { get; set; } }
the list order it's based on property of t
.
class bigroom { var room = new room(new list<something>()); } class room<t> t: class, new() { list<t> baselist; public room(list<t> listpar) { baselist = listpar; var prop = /* property t reflection... */ // how set comparer here, if know prop (type, value...) baselist.sort(...); // go reordered list } }
i can knowing t
, properties, using lambda expressions or delegates.
list.sort((x, y) => x.compareto(y));
but when getting prop
values, returns object
, doesn't implement compareto()
, there way of achieving this, if i'll grateful.
this should started. you'll need clean compare
method handle if values null i.e. either weren't set or not icomparable
required able comparisons.
propertyinfo mypropertyfromreflection = getmypropertysomehow(); mylist.sort(new mycomparer<transactionrequest>(mypropertyfromreflection)); public class mycomparer<t> : icomparer<t> { propertyinfo _sortby; public mycomparer(propertyinfo sortby) { _sortby = sortby; } public int compare(t x, t y) { var xvalue = _sortby.getvalue(x) icomparable; var yvalue = _sortby.getvalue(y) icomparable; homecoming xvalue.compareto(yvalue); } }
c# linq sorting generics reflection
Comments
Post a Comment