假设我有一个具有以下属性的对象。
public string VendorNumber { get; set; }
public string PartNumber { get; set; }
public string PartDivision { get; set; }
我有一个大约 300 个这些对象的列表。我试图先按 VendorNumber 对它们进行分组,然后按 Division 对它们进行分组。之后我应该能够像这样钻入它们:
- 供应商 A
第 1
部分 -- 第 0001
部分 -- 第 0002
部分 -- 第 0003
部分 第 2
部分 -- 第 0001 部分 - Vendor B
Division 1
--Part 0023 ...等...
我可以像这样轻松地进行第一个分组:
var vendorGroups =
from v in vendors
group v by v.VendorNumber into vg
select new { VendorNumber = vg.Key, Parts = vg, Count = vg.Count() };
即使参考了此处和 MSDN 上的其他一些帖子,我似乎也无法使嵌套分组工作。谢谢。
以下是我从建议中得出的结论:
我使用建议取得了一些进展,但循环时似乎无法访问第二级:
var vendorGroups = forecastHelpers
.GroupBy(x => new { VendorNumber = x.VendorNumber, Division = x.PartDivision, Level = 1 })
.GroupBy(x => new { VendorNumber = x.Key.VendorNumber }).OrderBy(x => 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);
}
}
}
更新 2:这也可以这样写:
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);
}
}