I know in normal Linq grammar, orderby xxx descending
is very easy, but how do I do this in Lambda expression?
Asked
Active
Viewed 3.5e+01k times
6 Answers
442
As Brannon says, it's OrderByDescending
and ThenByDescending
:
var query = from person in people
orderby person.Name descending, person.Age descending
select person.Name;
is equivalent to:
var query = people.OrderByDescending(person => person.Name)
.ThenByDescending(person => person.Age)
.Select(person => person.Name);

Jon Skeet
- 1,421,763
- 867
- 9,128
- 9,194
-
8"order by person.Name descending" should be "*orderby* person.Name descending" – mxmissile Jul 19 '11 at 18:59
22
Try this:
List<int> list = new List<int>();
list.Add(1);
list.Add(5);
list.Add(4);
list.Add(3);
list.Add(2);
foreach (var item in list.OrderByDescending(x => x))
{
Console.WriteLine(item);
}

Paul Zahra
- 9,522
- 8
- 54
- 76
16
Try this another way:
var qry = Employees
.OrderByDescending (s => s.EmpFName)
.ThenBy (s => s.Address)
.Select (s => s.EmpCode);

Paul Zahra
- 9,522
- 8
- 54
- 76

Sujit
- 3,677
- 9
- 41
- 50
3
This only works in situations where you have a numeric field, but you can put a minus sign in front of the field name like so:
reportingNameGroups = reportingNameGroups.OrderBy(x=> - x.GroupNodeId);
However this works a little bit different than OrderByDescending
when you have are running it on an int?
or double?
or decimal?
fields.
What will happen is on OrderByDescending
the nulls will be at the end, vs with this method the nulls will be at the beginning. Which is useful if you want to shuffle nulls around without splitting data into pieces and splicing it later.

Alexander Ryan Baggett
- 2,347
- 4
- 34
- 61