LINQ的多重订购 [英] Multiple Order By with LINQ

查看:52
本文介绍了LINQ的多重订购的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我首先要使用LINQ在List中进行操作的基本类,如下所示:

I start with a basic class that I want to manipulate in a List using LINQ, something like the following:

public class FooBar   
{  
    public virtual int Id { get; set; }  
    public virtual string Foo { get; set; }  
    public virtual string Bar { get; set; }
}

这就是我最终发现使用非lambda LINQ东西解决我的问题的原因.

This is what I ultimately found out to solve my problem using the non lambda LINQ stuff.

// 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  
}

我真正好奇的是,是否可以使用通用IEnumerable之外的基于Lambda的扩展方法来完成相同的事情. Google告诉我,我可以执行以下操作来实现它:

What I'm really curious about is if the same can be accomplished using the Lambda based extension methods off of generic IEnumerable to accomplish the same thing. Google tells me I can do something like the following to accomplish it:

var resultSet = foobarList.OrderBy(x => new {x.Foo, x.Bar})  
                          .Select(x=>x);

但是,如果执行此操作,则在我按下foreach语句时会收到运行时错误.该错误告诉我,至少一个对象必须实现IComparible,由于我为.OrderBy()方法使用了匿名类型,因此我可以看到这一点.

However if I do that I get a runtime error when I hit the foreach statement. 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.

那么有什么方法可以使用Lambda方法完成我想要的吗?

So is there a way to accomplish what I want using the Lambda way?

推荐答案

您可以使用 ThenByDescending 扩展方法:

You can use the ThenBy and ThenByDescending extension methods:

foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)

这篇关于LINQ的多重订购的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆