sharpecheddar
sharpecheddar

Reputation: 105

How to use conditional statements in mvc orderBy to move the 0 value last

super fresh coder here,

Currently I am using a foreach loop in my view to generate sections based on the model's position value. If the position is zero, the model is in development. I am trying to get the 0 values to show up last in an orderBy statement, but I can't seem to find the answer. Is there a more efficient way to accomplish my task? Here is my current syntax:

@foreach (var item in Model.OredrBy( model => model.Position))
{
    <div></div>
}

Upvotes: 0

Views: 211

Answers (3)

sharpecheddar
sharpecheddar

Reputation: 105

Thanks for the help everyone, I actually managed to solve this myself. Keeps descending order, but puts zeros last.

My solution:

OrderBy(a => a.Position == 0).ThenBy(a => a.Position).ToArrayAsync()

Upvotes: 1

TejSoft
TejSoft

Reputation: 3315

You can try this:

@{
    var orderedModel =  Model.OrderByDescending(model => model.Position).ToList();
    foreach(var item in orderedModel)
    {
        <div></div>
    }
}

Upvotes: 0

Peri
Peri

Reputation: 574

model => ( ( model.Position == 0 ) ? int.MaxValue : model.Position )

Upvotes: 1

Related Questions