Consider the following model:
public class Form
{
public Guid Id
{
get;
set;
}
public List<Section> Sections
{
get;
set;
}
}
public class Section
{
public Guid Id
{
get;
set;
}
public List<Question> Questions
{
get;
set;
}
public int SortOrder
{
get;
set;
}
}
public class Question
{
public Guid Id
{
get;
set;
}
public int SortOrder
{
get;
set;
}
}
When I retrieve one or more Form
objects using LINQ to Entities, I would like to have the associated collection of Section
objects sorted by the SortOrder
property. Further, within each of these Section
objects, I would like to have the associated collection of Question
objects sorted in the same fashion.
I don't recall where I read it, but I have been able to get the first-level sort to work using a LINQ query similar to the following:
var query =
from
f in context.Form
where
f.Id == *some form id*
select
new
{
Root = f,
Sections = f.Sections.OrderBy(s => s.SortOrder)
};
From there, I could get the actual Form
object by using something like:
var form = query.ToList().Select(q => q.Root).FirstOrDefault();
What I cannot figure out is how to write the LINQ query to extend this behavior down to the second-level collection (the collection of Question
objects within each Section
object.
* UPDATE *
See my comment to Ivan below which explains how this question is not a duplicate.