0

Is there a way to order a collection by two properties? For example:

I have a PriorityProcess class, and I want to order a collection of these instances by priority (descending) and then arrival time (ascending), but I want this last sort not to overwrite the previous one, more like a sub-sort.

Suppose I have this array of processes:

  1. P0 -> Priority = 1, Arrival Time = 0
  2. P1 -> Priority = 2, Arrival Time = 3
  3. P2 -> Priority = 1, Arrival Time = 8
  4. P3 -> Priority = 3, Arrival Time = 16

I would like to sort it, so I end up with this:

  1. P3 -> Priority = 3, Arrival Time = 16
  2. P1 -> Priority = 2, Arrival Time = 3
  3. P0 -> Priority = 1, Arrival Time = 0
  4. P2 -> Priority = 1, Arrival Time = 8

Is there a way to accomplish this in a single LINQ instruction?

Thanks for your time

Matias Cicero
  • 21,834
  • 10
  • 67
  • 132

1 Answers1

5

In sql syntax it is simply

from p in priorityProcesses
orderby p.Priority descending, p.ArrivalTime
select p;

In method syntax:

priorityProcesses
  .OrderByDescending(p => p.Priority)
  .ThenBy(p => p.ArrivalTime);
Dennis_E
  • 8,332
  • 20
  • 27