views:

395

answers:

1

Table Category (c) has a 1:many relationship with Table Question: a Category can have many Questions but a Question belongs only to one category. The questions are also ranked in terms of difficulty.

I would like a LINQ to EF query that would return all Categories with related Questions but the Questions should be sorted ascending in terms of difficulty (lets say on the Question.Rank column).

My query so far, is missing the sorted of the questions:

var results = from c in context.Category.Include("Question") select c;

How needs to be added to get the questions sorted?

+1  A: 

The standard way to order records is to use the orderby statement. See:

http://srtsolutions.com/blogs/billwagner/archive/2006/03/29/ordering-linq-results.aspx

Your problem is a little different since you are trying to order a sub list.

If you use the orderby together with the Loadwith it should work:

http://social.msdn.microsoft.com/Forums/en-US/linqprojectgeneral/thread/ec54792f-1ffb-45c3-9525-797c96023de9

http://social.msdn.microsoft.com/forums/en-US/linqtosql/thread/adbd8e6a-2679-4d03-98fe-c4ed7726f95d/

With some luck the code should look something like this:

var results = from c in context.Category 
 select new { Category = c, Question = c.Question.OrderBy(o => o.Rank) };
Shiraz Bhaiji
Thanks. That worked. As a follow-up, I want to assign results to a a variable like this:List<Category> categories;categories = results.ToList();Unfortunately, that results in "Error 1 Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#1>' to 'System.Collections.Generic.List<WoJ.Category>'"Any idea? Sorry, I'm new to generics.
Sajee
The anonymous type is coming from the "select new". You could do a for each over the results, create a Category object, assign values and add them to the list manually. Alternativily, you could use the LoadWith option that I have linked to.
Shiraz Bhaiji