262

I know in normal Linq grammar, orderby xxx descending is very easy, but how do I do this in Lambda expression?

RokumDev
  • 367
  • 4
  • 13
silent
  • 3,964
  • 5
  • 27
  • 29

6 Answers6

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
64

Use System.Linq.Enumerable.OrderByDescending()?

For example:

var items = someEnumerable.OrderByDescending();
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Brannon
  • 25,687
  • 5
  • 39
  • 44
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);

Queryable.ThenBy

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
1

LastOrDefault() is usually not working but with the Tolist() it will work. There is no need to use OrderByDescending use Tolist() like this.

GroupBy(p => p.Nws_ID).ToList().LastOrDefault();
Fuzzybear
  • 1,388
  • 2
  • 25
  • 42
Kawindu
  • 31
  • 1