通过按Lambda表达式降序?


250

我知道在通常的Linq语法中,orderby xxx descending这很容易,但是如何在Lambda表达式中做到这一点?

Answers:


428

正如布兰农说,这是OrderByDescendingThenByDescending

var query = from person in people
            orderby person.Name descending, person.Age descending
            select person.Name;

等效于:

var query = people.OrderByDescending(person => person.Name)
                  .ThenByDescending(person => person.Age)
                  .Select(person => person.Name);

7
“为了通过person.Name降”应为“ 排序依据 person.Name降”
mxmissile

63

使用System.Linq.Enumerable.OrderByDescending()

例如:

var items = someEnumerable.OrderByDescending();

21

试试这个:

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

14

尝试另一种方式:

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

可查询


3

这仅在具有数字字段的情况下有效,但是您可以在字段名称前加上减号,如下所示:

reportingNameGroups = reportingNameGroups.OrderBy(x=> - x.GroupNodeId);

但是,这与OrderByDescendingint?or double?或or decimal?字段上运行它时有些不同。

将会发生的是,OrderByDescending空值将在结尾,而使用此方法,空值将在开头。如果您想在不重复数据的情况下改组空值,而不将数据拆分成多个部分,然后再进行拼接,则这很有用。


1

LastOrDefault()通常无法正常工作,但Tolist()可以正常使用。不需要OrderByDescending使用Tolist()这种用法。

GroupBy(p => p.Nws_ID).ToList().LastOrDefault();
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.