Jason MacKenzie
Jason MacKenzie

Reputation: 123

LINQ Multiple Order By

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

Upvotes: 3

Views: 799

Answers (3)

Jay
Jay

Reputation: 6294

Try this:

var pamphlets = (from i in db.Pamphlets.Include("Category").Include("Program")
                 orderby i.Category.CategoryID, i.PamphletName
                 select i).ToList();

Upvotes: 1

BrokenGlass
BrokenGlass

Reputation: 160992

How about:

var pamphlets = (from p in db.Pamphlets.Include("Category").Include("Program")
                orderby p.Category.CategoryName, p.PamphletName
                select p).ToList();

Upvotes: 1

Justin Niessner
Justin Niessner

Reputation: 245479

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();

Upvotes: 7

Related Questions