使用 LINQ 进行多重排序 [英] Multiple Order By with LINQ

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

问题描述

我从一个基本类开始,我想使用 LINQ 在列表中操作它,如下所示:

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  
}

我真正好奇的是,是否可以使用基于 Lambda 的扩展方法脱离通用 IEnumerable 来完成同样的事情.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?

推荐答案

您可以使用 ThenByThenByDescending 扩展方法:

You can use the ThenBy and ThenByDescending extension methods:

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

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

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