Home > OS >  Custom Sorting Numerical Objects With Zero Not being first
Custom Sorting Numerical Objects With Zero Not being first

Time:09-21

If I was to have a list of objects with the following properties:

SomeClass.ID
SomeClass.Name

The .ID can be an integer while .Name can be a string, is there a way to sort the objects so that any 0 .ID is sorted and placed AFTER the non-zero ID numbers?

CodePudding user response:

Yes, you can use System.Linq:

Dim sorted = From o In yourObjectList
             Order By o.Id = 0, o.Id
yourObjectList = sorted.ToList()  

That's a conditional order, because o.Id = 0 will evaluate to either True or False. You want the non-zero first, so order Ascending(default) since True is "greater than" False.

This is the same in the (in VB.NET ugly) method syntax:

yourObjectList = yourObjectList.
        OrderBy(Function(o) o.Id = 0).
        ThenBy(Function(o) o.Id).
        ToList()

You can also rewrite it to use the conditional operator, if that's clearer for you:

yourObjectList = yourObjectList.
        OrderBy(Function(o) If(o.Id = 0, 1, 0)).
        ThenBy(Function(o) o.Id).
        ToList()

The If-operator it treats Id's with zero as 1 and all others as 0, so the <> 0 will come first.

  • Related