Note that there are some explanatory texts on larger screens.

plurals
  1. PONested groups using linq?
    text
    copied!<p>Lets say I have an object with the following properties.</p> <pre><code> public string VendorNumber { get; set; } public string PartNumber { get; set; } public string PartDivision { get; set; } </code></pre> <p>I have a list of about 300 of these objects. I am trying to group them first by VendorNumber, then by Division. I should be able to drill into them like so afterwards:</p> <ol> <li>Vendor A<br> Divsion 1<br> --Part 0001<br> --Part 0002<br> --Part 0003<br> Divsiion 2<br> --Part 0001</li> <li>Vendor B<br> Division 1<br> --Part 0023 ...etc...</li> </ol> <p>I can do the first grouping easily like so: </p> <pre><code>var vendorGroups = from v in vendors group v by v.VendorNumber into vg select new { VendorNumber = vg.Key, Parts = vg, Count = vg.Count() }; </code></pre> <p>I can't seem to get the nested grouping working though even after referring to some other posts here and on the MSDN. Thanks.</p> <hr> <p>Here is what I ended up with from the suggestions: </p> <p>I have made some progress using suggestions but I can't seem to access the second level when looping: </p> <pre><code>var vendorGroups = forecastHelpers .GroupBy(x =&gt; new { VendorNumber = x.VendorNumber, Division = x.PartDivision, Level = 1 }) .GroupBy(x =&gt; new { VendorNumber = x.Key.VendorNumber }).OrderBy(x =&gt; x.Key.VendorNumber); foreach (var vendorGroup in vendorGroups) { System.Diagnostics.Debug.WriteLine("VendorNumber: " + vendorGroup.Key.VendorNumber); foreach (var divisionGroup in vendorGroup) { System.Diagnostics.Debug.WriteLine(" Division: " + divisionGroup.Key.Division); foreach (var partNumber in divisionGroup) { System.Diagnostics.Debug.WriteLine(" PartNumber: " + partNumber.PartNumber); } } } </code></pre> <hr> <p>Update 2: This could also be written like so:</p> <pre><code>var vendorGroupings = from f in forecastHelpers group f by new { VendorNumber = f.VendorNumber, Division = f.PartDivision, Level = 2 } into vendorGroups from divisionGroups in (from division in vendorGroups orderby division.PartDivision group division by new { Division = division.PartDivision }) orderby vendorGroups.Key.VendorNumber group divisionGroups by new { VendorNumber = vendorGroups.Key.VendorNumber, Level = 1 }; foreach (var vendorGroup in vendorGroupings) { System.Diagnostics.Debug.WriteLine("VendorNumber: " + vendorGroup.Key.VendorNumber); foreach (var division in vendorGroup) { System.Diagnostics.Debug.WriteLine(" Division: " + division.Key.Division); foreach (var part in division) { System.Diagnostics.Debug.WriteLine(" PartNumber: " + part.PartNumber); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload