.net - C# List<> Sort by x then y -
similar list<> orderby alphabetical order, want sort 1 element, another. want achieve functional equivalent of
select * table order x, y
we have class contains number of sorting functions, , have no issues sorting 1 element.
example:
public class myclass { public int x; public int y; } list<myclass> mylist; public void sortlist() { mylist.sort( mysortingfunction ); }
and have following in list:
unsorted sorted(x) desired --------- --------- --------- id x y id x y id x y [0] 0 1 [2] 0 2 [0] 0 1 [1] 1 1 [0] 0 1 [2] 0 2 [2] 0 2 [1] 1 1 [1] 1 1 [3] 1 2 [3] 1 2 [3] 1 2
stable sort preferable, not required. solution works .net 2.0 welcome.
do keep in mind don't need stable sort if compare members. 2.0 solution, requested, can this:
public void sortlist() { mylist.sort(delegate(myclass a, myclass b) { int xdiff = a.x.compareto(b.x); if (xdiff != 0) return xdiff; else return a.y.compareto(b.y); }); }
do note 2.0 solution still preferable on popular 3.5 linq solution, performs in-place sort , not have o(n) storage requirement of linq approach. unless prefer original list object untouched of course.
Comments
Post a Comment