使用 LINQ 进行多重排序
我从一个基本类开始,我想使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 ThenBy 和 ThenByDescending 扩展方法:
You can use the ThenBy and ThenByDescending extension methods: