OrderBy descending in Lambda expression?

后端 未结 6 1510
梦谈多话
梦谈多话 2020-12-02 05:12

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

相关标签:
6条回答
  • 2020-12-02 05:51

    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();
    
    0 讨论(0)
  • 2020-12-02 05:55

    Use System.Linq.Enumerable.OrderByDescending()?

    For example:

    var items = someEnumerable.OrderByDescending();
    
    0 讨论(0)
  • 2020-12-02 06:02

    Try this another way:

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

    Queryable.ThenBy

    0 讨论(0)
  • 2020-12-02 06:06

    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);
    
    0 讨论(0)
  • 2020-12-02 06:06

    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);                
    }
    
    0 讨论(0)
  • 2020-12-02 06:14

    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.

    0 讨论(0)
提交回复
热议问题