Multiple Order By with LINQ

C#LinqLambda

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

You can use the ThenBy and ThenByDescending extension methods:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsdannaView Question on Stackoverflow
Solution 1 - C#Pop CatalinView Answer on Stackoverflow