Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Multiple Order By

Tags:

c#

linq

I have 3 tables Pamphlets, Categories and Program. The Pamphlet table has a CategoryID and ProgramID column. The following code works:

var pamphlets = db.Pamphlets.Include("Category").Include("Program").ToList();

What I need to do is sort by CategoryName (Category table) and then PamphletName (Pamphlet table).

like image 402
Jason MacKenzie Avatar asked Jan 31 '26 12:01

Jason MacKenzie


2 Answers

You would simply chain a call to ThenBy():

var sortedPamphlets = db.Pamphlets.Include("Category").Include("Program")
                        .OrderBy(p => p.Category.CategoryName)
                        .ThenBy(p => p.PamphletName)
                        .ToList();
like image 200
Justin Niessner Avatar answered Feb 03 '26 02:02

Justin Niessner


How about:

var pamphlets = (from p in db.Pamphlets.Include("Category").Include("Program")
                orderby p.Category.CategoryName, p.PamphletName
                select p).ToList();
like image 40
BrokenGlass Avatar answered Feb 03 '26 00:02

BrokenGlass