How can I sort but put zeros at the bottom?

I have a list of objects that have a Rank property. This is an integer.

I want to sort by rank on my view, but when I do this:

myObjects = myObjects.Orderby(r=>r.Rank); 

i get all zeros (which means they were not set at the top)

I want to order 1 → n, but zeros will be at the bottom of the list.

I would like it to be as effective as possible, since the list is quite long

+6
source share
3 answers

LINQ:

 myObjects = myObjects .OrderBy(r => r.Rank == 0) //false before true .ThenBy(r => r.Rank); 

In fact, this will not do two complete sorts. It will combine two lambdas into one dictionary, sorting by two keys.

If you are not comfortable using the less obvious rule false -before- true , can you replace the first lambda with r => r.Rank == 0 ? 1 : 0 r => r.Rank == 0 ? 1 : 0 - but knowing false -before- true makes this really redundant.

+18
source

You can create your own IComparer (implementing IComparer ) and sort the zeros at the bottom. Pseudocode:

 public class ZeroComparer : IComparer { public int Compare(Object intA, Object intB) { if(intA == 0 && intB != 0) return -1; if(intA != 0 && intB == 0) return 1; return int.Compare(intA, intB); } } 

Then use it like:

 var comparer = new ZeroComparer(); myObjects = myObjects.Orderby(r=>r.Rank, comparer); 

A quick example of using custom mappings:

Use custom IComparer <T> with Linq OrderBy

+6
source
 myObjects = myObjects.Orderby(r => r.Rank == 0 ? int.MaxValue : r.Rank); 

to consider the case of Rank == int.MaxValue :

 myObjects = myObjects.Orderby(r => r.Rank == 0 ? int.MaxValue : r.Rank - 1); 
+1
source

Source: https://habr.com/ru/post/945635/


All Articles