Advertisement
Advertisement


OrderBy descending in Lambda expression?


Question

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

2016/06/26
1
251
6/26/2016 3:17:27 PM

Accepted Answer

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);
2011/07/19
428
7/19/2011 7:01:55 PM

Use System.Linq.Enumerable.OrderByDescending()?

For example:

var items = someEnumerable.OrderByDescending();
2018/10/19

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);                
}
2017/12/15

Try this another way:

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

Queryable.ThenBy

2017/12/15

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.


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();
2018/05/18

Source: https://stackoverflow.com/questions/1635497
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]