这是我的代码中的数据表:
PackID PackName FilterID SystemID SystemName
18 ThirdRep 0 5 ABC
18 ThirdRep 1 5 ABC
18 ThirdRep 3 3 XYZ
17 SecondRep 0 5 ABC
我需要对Package下的所有系统进行分组,并将Linq中系统下的所有过滤器分组。我想将这些数据转换如下。
包的集合(预期结果的一个例子):
PackageID :17
PackName :SecondRep
SystemCollection [ SystemID:5 , SystemName : ABC, FilterCollection [FilterID:1,FilterID:0 ] ]
PackageID :18
PackName :ThirdRep
SystemCollection [ SystemID:5 , SystemName : ABC, FilterCollection [FilterID:0 ] ]
我的代码:
var groupedData = from b in dataset.Tables[0].AsEnumerable()
group b by new
{
PackageID = b.Field<Int32>("PackageID"),
PackageName = b.Field<string>("PackageName"),
} into g
select new ReportPackage
{
PackageId = g.Key.PackageID,
PackageName = g.Key.PackageName,
SystemCollection = g.Select(c => new ReportSystem
{
SystemId = c.Field<int>("SystemID"),
SystemName = c.Field<string>("SystemName"),
FilterCollection = g.Select(b => new ReportFilter
{
FilterId = b.Field<int>("FilterID"),
}).ToList()
}).GroupBy(x => x.SystemId).Select(v => v.First()).ToList()
};
以上代码对我没什么帮助。无论系统ID如何,所有过滤器都会添加到集合中。
答案 0 :(得分:0)
您应首先按SystemID
和SystemName
对过滤器进行分组,然后执行选择,而不是相反。
尝试:
var groupedData = from b in dataset.Tables[0].AsEnumerable()
group b by new
{
PackageID = b.Field<int>("PackageID"),
PackageName = b.Field<string>("PackageName"),
} into g
select new ReportPackage
{
PackageId = g.Key.PackageID,
PackageName = g.Key.PackageName,
SystemCollection = (from e in g
group e by new
{
SystemID = b.Field<int>("SystemID"),
SystemName = b.Field<string>("SystemName")
} into fg
select new ReportSystem
{
fg.SystemID,
fg.SystemName,
FilterCollection = fg.Select(f => new ReportFilter
{
FilterID = f.Field<int>("FilterID")
}
}).ToList()
}