本文介绍了LINQ的OrderBy与多个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我需要两个字段排序的列表。我已经使用排序依据试图LINQ但只允许我指定一个字段。我正在寻找列表由第一场进行排序,然后,如果有在第一个字段任何重复到由第二场进行排序。

例如我想要的结果看起来像这样(按姓氏然后名字排序)。


  • 亚当斯,约翰·

  • 史密斯,詹姆斯

  • 史密斯,彼得

  • 汤普森,弗雷德

我已经看到了你可以使用但我在寻找一种方式与方法排序依据来做到这一点。

 的IList<&人GT; listOfPeople = / *名单某种程度上填补。* /
IEnumerable的<&人GT; sortedListOfPeople = listOfPeople.OrderBy(aPerson => aPerson.LastName,aPerson.FirstName); //这是行不通的。


解决方案

您需要使用:

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

I have a list that I need sorted by two fields. I've tried using OrderBy in LINQ but that only allows me to specify one field. I'm looking for the list to be sorted by the first field and then if there are any duplicates in the first field to sort by the second field.

For example I want the results to look like this (sorted by last name then first name).

  • Adams, John
  • Smith, James
  • Smith, Peter
  • Thompson, Fred

I've seen that you can use the SQL like syntax to accomplish this but I am looking for a way to do it with the OrderBy method.

IList<Person> listOfPeople = /*The list is filled somehow.*/
IEnumerable<Person> sortedListOfPeople = listOfPeople.OrderBy(aPerson => aPerson.LastName, aPerson.FirstName); //This doesn't work.
解决方案

You need to use ThenBy:

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

这篇关于LINQ的OrderBy与多个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 04:27