具有多个字段的 LINQOrderBy

我有一个需要按两个字段排序的列表。我试过在 LINQ 中使用 OrderBy,但它只允许我指定一个字段。我正在寻找的列表排序的第一个字段,然后如果有任何重复的第一个字段排序的第二个字段。

例如,我希望结果看起来像这样(按姓排序,然后按名排序)。

  • 亚当斯,约翰
  • 史密斯,詹姆斯
  • 史密斯,彼得
  • 汤普森,弗雷德

我已经看到您可以使用 类似 SQL 的语法来实现这一点,但是我正在寻找一种使用 OrderBy 方法的方法。

IList<Person> listOfPeople = /*The list is filled somehow.*/
IEnumerable<Person> sortedListOfPeople = listOfPeople.OrderBy(aPerson => aPerson.LastName, aPerson.FirstName); //This doesn't work.
90018 次浏览

You need to use ThenBy:

listOfPeople.OrderBy(person => person.LastName)
.ThenBy(person => person.FirstName)

Use .ThenBy(aPerson=>field2);

var sortedListOfPeople = listOfPeople.OrderBy(aPerson => aPerson.LastName).ThenBy(a => aPerson.FirstName);

Your subsequent fields should be ordered by using the ThenBy() method

If you want to use method syntax, use ThenBy(), as others suggested:

listOfPeople.OrderBy(person => person.LastName)
.ThenBy(person => person.FirstName)

In query syntax, the same can be accomplished pretty much the way you wanted: two sort keys separated by a comma:

from person in listOfPeople
orderby person.LastName, person.FirstName
select person

The above code will be actually compiled to code that uses OrderBy() and ThenBy(), as in the first example.

Also, if you'd like to have OrderBy() that takes two (or more) sort keys, you can certainly write that as an extension method on IEnumerable<T> that internally calls OrderBy() and ThenBy().

The way to order a list with more filed is the follow:

var soterdList = initialList.OrderBy(x => x.Priority).
ThenBy(x => x.ArrivalDate).
ThenBy(x => x.ShipDate);

You can add other fields with clasole "ThenBy"