Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort but put zeros at the bottom?

Tags:

c#

sorting

linq

I have a list of objects that have a property Rank. 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 of the zeros (meaning these haven't been set at the top)

I want to order by 1 --> n but have the zeros be at the bottom of the list.

I would like it to be as efficient a sort as possible as the list is quite long

like image 513
leora Avatar asked May 22 '13 21:05

leora


2 Answers

LINQ:

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

This won't actually do two full sorts. It will combine the two lambdas into a single dictionary sort across the two keys.

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

like image 132
Timothy Shields Avatar answered Sep 23 '22 06:09

Timothy Shields


You can create a custom comparer (implementing IComparer) and have it sort zeroes to the bottom. The pseudo code would be:

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 how to use custom comparers:

Use own IComparer<T> with Linq OrderBy

like image 21
ean5533 Avatar answered Sep 25 '22 06:09

ean5533