使用 LINQ 进行多重排序

发布于 2024-08-22 05:32:40 字数 1157 浏览 2 评论 0原文

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

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

这是我最终发现使用非 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  
}

我真正好奇的是,是否可以使用通用 IEnumerable 的基于 Lambda 的扩展方法来完成同样的事情。谷歌告诉我,我可以执行如下操作来完成它:

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

但是,如果我这样做,当我点击 foreach 语句时,我会收到运行时错误。该错误告诉我,至少有一个对象必须实现 IComparible,我可以看到这一点,因为我在 .OrderBy() 方法中使用了匿名类型。

那么有没有办法使用 Lambda 方式来完成我想要的事情呢?

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

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  
}

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);

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.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

半岛未凉 2024-08-29 05:32:40

您可以使用 ThenByThenByDescending 扩展方法:

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

You can use the ThenBy and ThenByDescending extension methods:

foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文