OrderBy descending in Lambda expression?

LinqLambda

Linq Problem Overview


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

Linq Solutions


Solution 1 - Linq

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);

Solution 2 - Linq

Use System.Linq.Enumerable.OrderByDescending()?

For example:

var items = someEnumerable.OrderByDescending();

Solution 3 - Linq

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);                
}

Solution 4 - Linq

Try this another way:

var qry = Employees
          .OrderByDescending (s => s.EmpFName)
          .ThenBy (s => s.Address)
          .Select (s => s.EmpCode);

Queryable.ThenBy

Solution 5 - Linq

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.

Solution 6 - Linq

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();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsilentView Question on Stackoverflow
Solution 1 - LinqJon SkeetView Answer on Stackoverflow
Solution 2 - LinqBrannonView Answer on Stackoverflow
Solution 3 - LinqAnton PView Answer on Stackoverflow
Solution 4 - LinqSujitView Answer on Stackoverflow
Solution 5 - LinqAlexander Ryan BaggettView Answer on Stackoverflow
Solution 6 - LinqKawinduView Answer on Stackoverflow