Problem
I begin with a simple class that I wish to manipulate in a List using LINQ, such as this:
public class FooBar
{
public virtual int Id { get; set; }
public virtual string Foo { get; set; }
public virtual string Bar { get; set; }
}
This is how I was able to fix my difficulty with the non-lambda LINQ stuff in the end.
// 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 actually curious about is whether the same thing can be performed with Lambda-based extension methods off of generic IEnumerable. 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, when I reach the foreach statement, I receive a runtime error. Because I’m using an anonymous type for the, the error tells me that at least one object must implement IComparable. The OrderBy() method is used to sort data.
Is there a way to achieve what I’m looking for using Lambda?
Asked by sdanna
Solution #1
ThenBy and ThenByDescending extension methods can be used:
foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)
Answered by Pop Catalin
Post is based on https://stackoverflow.com/questions/2318885/multiple-order-by-with-linq