Consider the following simplified objects and relationships:
public class Job{ int JobId; String name; String status; Discipline disc; WorkCategory workCat; } public class Discipline { int DisciplineId; String DisciplineName; } public class Workcategory{ int WorkCategoryId; String WorkCategoryName; } public Class Grouping{ Discipline parent; List<Workcategory> children; }
The above model is related to the fact that a Job is associated with one Discipline and one WorkCategory . WorkCategory always a child of a specific parent Discipline (one-to-many relationship). We can assume that the relationship between the assigned discipline and the working category will always be valid.
The problem I am facing is when I try to create a Grouping result Grouping based on the filters that apply to Jobs . I am not sure if this can be done or if the approach I am taking is even correct. The exact question itself is not clear, but the above determines the formulation of the problem.
- Can the design be improved?
- How can I group assignments by discipline and work category?
- Do I need a
Grouping class?
I tried the following (this is my first attempt using Linq), but to no avail since my understanding is not complete enough. Another alternative is to get a Discipline group and loop through the original grouping that collects the corresponding WorkCategory .
var grouping = repository.GetJobsWithActiveStatus() .GroupBy(x => new { x.Discipline.DisciplineID, x.Discipline.DisciplineName, x.Category.WorkCategoryID, x.Category.WorkCategoryName }) .Select(g => new Grouping{ Discipline = new Discipline{ DisciplineID = g.Key.DisciplineID, Name = g.Key.DisciplineName }, Categories = ??
Edit: After posting this post, I realized that the inital GroupBy parameters result in one group of elements, while I am looking for the result of Group-SubGroup.
Edit 2: To clarify things a bit more, I donβt want related tasks to be performed as part of the result, but rather the Discipline-Workcategory group - therefore the reason for the Grouping class
Original solution based on @Obalix
Change 7-Mar-2010:
This solution does not work - GroupBy on the Discipline object will give a unique grouping for each object. I think this is due to the fact that it is a reference type. I'm right? At first, I accepted this as an answer, but after some head realized that my layout data itself was erroneous. Initial questions are still answered.
var result = repository.GetJobsWithActiveStatus() .GroupBy(x => x.disc) .Select(g => new Grouping { Discipline = g.Key, Catergories = g.GroupBy(x=>x.workCat)