C# 使用 LINQ 进行多重排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/2318885/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multiple Order By with LINQ
提问by sdanna
I start with a basic class that I want to manipulate in a List using LINQ, something like the following:
我从一个我想使用 LINQ 在 List 中操作的基本类开始,如下所示:
public class FooBar   
{  
    public virtual int Id { get; set; }  
    public virtual string Foo { get; set; }  
    public virtual string Bar { get; set; }
}
This is what I ultimately found out to solve my problem using the non lambda LINQ stuff.
这就是我最终发现使用非 lambda LINQ 来解决我的问题的方法。
// code somewhere else that works and gets the desired results  
var foobarList = GetFooBarList();  // Abstracted out - returns List<Foobar>  
// Interesting piece of code that I want to examine
var resultSet = from foobars in foobarList  
                orderby foobars.Foo, foobars.Bar  
                select foobars;
// Iterate and do something interesting  
foreach (var foobar in resultSet)  
{  
    // Do some code  
}
What I'm really curious about is if the same can be accomplished using the Lambda based extension methods off of generic IEnumerableto accomplish the same thing.  Google tells me I can do something like the following to accomplish it:
我真正好奇的是,是否可以使用基于 Lambda 的扩展方法IEnumerable来完成相同的事情。Google 告诉我我可以执行以下操作来完成它:
var resultSet = foobarList.OrderBy(x => new {x.Foo, x.Bar})  
                          .Select(x=>x);
However if I do that I get a runtime error when I hit the foreachstatement.  The error tells me that at least one object has to implement IComparible, which I can see that since I'm using an anonymous type for the .OrderBy()method.
但是,如果我这样做,当我点击foreach语句时会出现运行时错误。该错误告诉我至少有一个对象必须实现IComparible,我可以看到这一点,因为我为该.OrderBy()方法使用了匿名类型。
So is there a way to accomplish what I want using the Lambda way?
那么有没有办法使用 Lambda 方式来完成我想要的?
采纳答案by Pop Catalin
You can use the ThenByand ThenByDescendingextension methods:
您可以使用ThenBy和ThenByDescending扩展方法:
foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)

