3

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

1

3 Answers 3

7

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();
Sign up to request clarification or add additional context in comments.

3 Comments

Wouldn't it be better to place OrderBy before ToList to give database a chance?
@Snowbear JIM-compiler - We had the same thought at the same time. Just made the change before I saw your comment.
Thanks! I really appreciate that. I knew it must be something simple.
1

How about:

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

Comments

1

Try this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.