How to order a collection and its subset using LINQ?

I have a collection of employees, and each employee has his own responsibility. I would like to list employees sorted by name, and list their duties sorted by title.

So, it should be displayed as follows:


Jane jones

Duties:

Responsibility A

Responsibility B

Mike smith

Duties:

Responsibility A

Responsibility C


To get the initial collection, I use:

var employees = _context.Employees.OrderBy(e => e.Name); 

but I can't figure out how to organize the Responsibilities subcollection.

I use MVC and my View gets a strongly typed collection of Employee, so I don't want to create and return an anonymous type.

+6
collections linq order
source share
2 answers

You can do something like:

 var employees = _context.Employees.OrderBy(e => e.Name); employees.ToList().ForEach(e => e.Responsibilities = e.Responsibilities.OrderBy(r => r.Name)); 
+3
source share

1st approach: (only suitable for LINQ for objects with responsibility defined as IList)

You can copy Employees to the new collection, but that means you need to copy each field to a new employee, something like this:

 var employees = from e in _context.Employees orderby e.Name select new Employee { Name = e.Name, ...re-assign other properties... Responsibilities = e.Responsibilities.OrderBy(r => r.Name).ToList() }; 

Second approach:

Using DataLoadOptions . Basically, you create a DataLoadOptions object that indicates how to arrange a specific relationship, so in your case:

 var options = new DataLoadOptions(); options.AssociateWith<Employees>(e => e.Responsibilities.OrderBy(r => r.Name)); _context.LoadOptions = options; var employees = _context.Employees.OrderBy(e => e.Name); 

Duties will be ordered automatically.

+2
source share

All Articles