-2

Is there a way to apply OrderBy on IQueryable starting by a specific value?

Ex: I have this follow entity

Name   | Age  | Type |
Marcos |  15  |  1   |
Andrew |  23  |  2   |
Phelip |  18  |  2   |
Jhonny |  14  |  3   |

I've tried the following code, but it didn't work:

var result =  Query.OrderBy(x => x.Type == 2);

Any Idea?

FCin
  • 3,804
  • 4
  • 20
  • 49
  • 3
    Can you explain _"it didn't work"_? Please provide your expected output and actual output so we can help get you to where you want to be. – dvo Aug 21 '19 at 13:17
  • 1
    Why do you have `x => x.Type == 2` should you just have `x => x.Type` instead? – Johnny Aug 21 '19 at 13:22
  • Try `Query.OrderByDescending(x => x.Type == 2);` if you want the rows where `Type == 2` at the top. – mm8 Aug 21 '19 at 13:22
  • Do you only want to display results that have `Type >= 2`? – haldo Aug 21 '19 at 13:23
  • What do you expect as an output: `1,2,2,3` or `2,2,1,3`? – Johnny Aug 21 '19 at 13:27

1 Answers1

2

I assume you want the list ordered like 2,2,1,3: all 2 records listed first, and the rest ordered normally.

This should do it:

var result =  Query.OrderBy(x => x.Type == 2 ? -1 : x.Type);

That will change the value that is used for ordering to -1 when Type is 2. Since -1 is less than all of your other values, they will show at the top of the list.

If you are going to have records where the Type is -1, then you need to choose a different value. It has to be something that is less than all other values.

Gabriel Luci
  • 38,328
  • 4
  • 55
  • 84
  • `Query.OrderByDescending(x => x.Type == 2).ThenBy(x => x.Type)` should also work. – mm8 Aug 21 '19 at 13:34
  • 1
    @mm8 That's a better solution as it doesn't rely on a "magic" number that is less than all the expected values. – juharr Aug 21 '19 at 13:40