Search code examples
c#linqgroup-bymany-to-many

LINQ - GroupBy over many-to-many relation


How to write GroupBy clause which will retrieve multiple records from many to many relation?

I have following structure:

 public class Failure{
    public virtual int IdFailure { get; set; }
    public virtual Workstation Workstation{ get; set; }
 }

 public class Workstation{
    public virtual int IdWorkstation { get; set; }
    public virtual IList<WorksocketWorkstation> WorksocketWorkstation { get; set; }
 }

 public class WorksocketWorkstation{
    public virtual int IdWorksocketWorkstation{ get; set; }
    public virtual Worksocket Worksocket{ get; set; }
    public virtual Workstation Workstation{ get; set; }
 }

 public class Worksocket {
    public virtual int IdWorksocket { get; set; }
    public virtual IList<WorksocketWorkstation> WorksocketWorkstation { get; set; }
 }

What I want to do is to group Failures by related Worksockets, including "duplicates" resulting from many-to-many relation, so if I have a Failure occuring on Workstation assigned to three Worksockets, I want it to be accounted for each of these Worksockets. Currently I'm using something like this to get my results:

GetFailures().GroupBy(g => g.Workstation.WorksocketWorkstation.FirstOrDefault().Worksocket.IdWorksocket)

But since I'm using FirstOrDefault, each Failure is accounted only for single Worksocket. I've tried to use SelectMany instead or get the data from the Worksockets side, based on the similar questions that have been already answered here, but I can't wrap my head around any of the ideas and adjust them to my needs, so any help or explanation would be greatly appreciated.


Solution

  • GetFailures().SelectMany(g => g.Workstation.WorksocketWorkstation)
                 .GroupBy(g => g.Worksocket.IdWorksocket)