sdanna sdanna - 1 year ago 100
C# Question

Multiple Order By with 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; }

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

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?

Answer Source

You can use the ThenBy and ThenByDescending extension methods:

foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download