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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With