277

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?

2
  • 3
    If you want to know what the "fluent methods" are corresponding to every possible query expression, read section 7.15.2 of the specification. Commented Feb 23, 2010 at 16:28
  • 2
    @Eric Lippert, there's a C# 3.0 Query Expression Translation Cheat Sheet, written by Bart Desmet, which I found very useful as a quick reference: bartdesmet.net/blogs/bart/archive/2008/08/30/… . Commented Feb 24, 2010 at 22:11

1 Answer 1

622

You can use the ThenBy and ThenByDescending extension methods:

foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)
Sign up to request clarification or add additional context in comments.

7 Comments

Guess I should fully get through the API before asking the question ;) It also looks like you can chain .ThenBy() statements as many times as you need to. Thanks again!
what about .AndThen()
No .AndThen()!
(function AndThen() { AndThen() })()
NOTE: .OrderBy() and .ThenBy() return an IOrderedEnumerable, which does not modify the original object. So, you need to assign to a variable and end with ToList() to use the new ordered list elsewhere.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.