Beau D'Amore
Beau D'Amore

Reputation: 3392

LINQ: sort child object param

I have 'Executive' objects that have X number of 'ExecutiveSectionMapping' child objects depending on how many sections that Executive belongs too.

Problem is, when viewing these Executives, the order of the mappings is random. I need to order the child's parameters independently of ordering the executives themselves. Tried this to no avail:

 return _context.Executives
            .OrderBy(x => x.ExecutiveSectionMappings.OrderBy(y=>y.ExecutiveSectionId))
            .ToList();

Tried this too:

return _context.Executives
            .OrderBy(x => x.ExecutiveSectionMappings.Select((y => y.ExecutiveSectionId)))
            .ToList();

and this:

     return _context.Executives
            .Include(x=>x.ExecutiveSectionMappings.OrderBy(y=>y.ExecutiveSectionId))
            .ToList();

not sure how to proceed... any ideas?

Upvotes: 1

Views: 44

Answers (1)

Marc Cals
Marc Cals

Reputation: 2989

It seems that this can't be done in your context, but it can be done in memory.

List<Executives> executives = _context.Executives.ToList();

executives.ForEach(e => 
    e.ExecutiveSectionMappings = e.ExecutiveSectionMappings.OrderBy(y=>y.ExecutiveSectionId)
   .ToList())

Upvotes: 1

Related Questions