Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to order by multiple columns using VB.Net lambda expressions

I've done a brief search of this site, and googled this, but can't seem to find a good example. I'm still trying to get my head around the whole "Lambda Expressions" thing.

Can anyone here give me an example ordering by multiple columns using VB.Net and Linq-to-SQL using a lambda expression?

Here is my existing code, which returns an ordered list using a single-column to order the results:

Return _dbContext.WebCategories.OrderBy(Function(c As WebCategory) c.DisplayOrder).ToList

Note: The WebCategory object has a child WebPage object (based on a foreign key). I'd like to order by WebPage.DisplayOrder first, then by WebCategory.DisplayOrder.

I tried chaining the order bys, like below, and though it compiled and ran, it didn't seem to return the data in the order I wanted.

Return _dbContext.WebCategories.OrderBy(Function(c As WebCategory) c.DisplayOrder).OrderBy(Function(c As WebCategory) c.WebPage.DisplayOrder).ToList

Thanks in advance.

like image 624
camainc Avatar asked Nov 16 '09 17:11

camainc


2 Answers

I found this MSDN article in a quick Google search. I guess what your looking for is this:

Return _dbContext.WebCategories.OrderBy(Function(c As WebCategory) c.DisplayOrder). _
ThenBy(Function(c As WebCategory) c.WebPage.DisplayOrder).ToList
like image 121
HuBeZa Avatar answered Oct 17 '22 13:10

HuBeZa


You should use ThenBy like this:

Return _dbContext.WebCategories.OrderBy(Function(c As WebCategory) c.DisplayOrder) _
                               .ThenBy(Function(c As WebCategory) c.WebPage.DisplayOrder) _
                               .ToList()
like image 20
Meta-Knight Avatar answered Oct 17 '22 11:10

Meta-Knight