Home > Software design >  Linq group by element and a sub element
Linq group by element and a sub element

Time:04-15

Structure is basically like this:

Master:

  Id 
  DocNo
  Laws[]

Laws is as follows:

LawNo
Id

I want to group by DocNo and LawNo.

The expected dictionary keys are:

{DocNo, LawNo}

And the expected value is

Master

I tried this but keys are not like the expected

master.GroupBy(x => new {x.DocNo, _LawNo = x.Laws.Select(y => y.LawNo).Distinct()});

Thanks

CodePudding user response:

If I understand correctly, you can try to use SelectMany before using GroupBy, SelectMany let LawNo flatten as DocNo

master.SelectMany(x=>x.Laws,(x,y)=>new{x.DocNo,y.LawNo})
      .GroupBy(x=> new {x.DocNo,x.LawNo});

CodePudding user response:

what I understood from this

 master
    .SelectMany(m => 
        m.Laws.Select(l => (Master : m, Law : l))
    .GroupBy(tuple => new { LawNo: tuple.Law.LawNo, DockNo: tuple.Master.DocNo})

Result should be groups of masters.

  • Related