代码之家  ›  专栏  ›  技术社区  ›  brainimus user417509

具有多个字段的LINQ OrderBy

  •  70
  • brainimus user417509  · 技术社区  · 14 年前

    例如,我希望结果是这样的(按姓氏排序,然后按名字排序)。

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

    我知道你可以用 SQL like syntax to accomplish this

    IList<Person> listOfPeople = /*The list is filled somehow.*/
    IEnumerable<Person> sortedListOfPeople = listOfPeople.OrderBy(aPerson => aPerson.LastName, aPerson.FirstName); //This doesn't work.
    
    6 回复  |  直到 7 年前
        1
  •  180
  •   tzaman    14 年前

    你需要使用 ThenBy :

    listOfPeople.OrderBy(person => person.LastName)
                .ThenBy(person => person.FirstName)
    
        2
  •  27
  •   svick Raja Nadar    12 年前

    如果要使用方法语法,请使用 ThenBy() ,正如其他人所建议的:

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

    在查询语法中,可以按照您想要的方式完成相同的操作:两个排序键用逗号分隔:

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

    OrderBy() ,如第一个示例所示。

    另外,如果你想 OrderBy() IEnumerable<T> 内部调用

        3
  •  3
  •   Coding Flow    14 年前

    后续字段应使用ThenBy()方法排序

        4
  •  2
  •   Robaticus    14 年前

    .ThenBy(aPerson=>field2);

        5
  •  2
  •   moi_meme    14 年前
    var sortedListOfPeople = listOfPeople.OrderBy(aPerson => aPerson.LastName).ThenBy(a => aPerson.FirstName);
    
        6
  •  2
  •   daniele3004    8 年前

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

    您可以使用clasole“ThenBy”添加其他字段