0

I'm trying to order by WeekId, then Order in my SQL table (end result should have workouts together by id, then ordered by the order specified), yet it is giving the wrong order. Is there something wrong with my LINQ statement?

private List<Workout> GetWorkouts(int id)
{
    return new OPPDBContext().Workouts
        .Where(p=>p.ClientId == id).OrderBy(p => p.Order).OrderBy(p => p.WeekId).ToList();
}

The table:

enter image description here

The results:

enter image description here

Expected results:

 Lat Pulldowns
 Squats
 Lat Pulldowns
 Squats
 Reverse Lunges
Uwe Keim
  • 36,867
  • 50
  • 163
  • 268

1 Answers1

2

That's because the second .OrderBy replaces the first .OrderBy (you are sorting by ClientId, and then effectively discard that to sort by WeekId).

You need to use .OrderBy(...).ThenBy(...) instead:

return new OPPDBContext().Workouts.Where(p=>p.ClientId == id).OrderBy(p => p.Order).ThenBy(p => p.WeekId).ToList();

OrderBy docs

ThenBy docs

Llama
  • 25,925
  • 5
  • 49
  • 68