我正在使用数据库应用程序,该数据库应用程序通过其标签显示了清晰的交易报告。
这是我的数据库。
Title Amount TagsReport (string[] array)
Food 5 "Hotel","Friends"
Food 6 "Hotel"
Family 8 "Hotel","Mobile"
Family 9 "Electricity"
Food 8 "Party"
我希望生成如下报告:
所需的输出:
Percentage Title Amount
53% Food 19
Hotel 11
Friends 5
Party 8
57% Family 17
Hotel 8
Mobile 8
Electricity 9
我对LINQ没有足够的了解。因此,在寻找完美解决方案的过程中,我面临很多麻烦。
但是我发现要使用此代码,
var ReportingData = ReportListQuery
.Where(Item => Item.Category == "expense")
.GroupBy(item => item.Title)
.Select(itemGroup => new
{
Percentage = Math.Round((itemGroup.Sum(item => item.Amount) / MonthExpense) * 100),
ExpenseTitle = itemGroup.Key,
ExpenseCalculation = itemGroup.Sum(item => item.Amount),
TotalTagAmounts = itemGroup
.SelectMany(item => item.TagsReport.Select(tag => new {
Tag = tag,
Amount = item.Amount
})
.GroupBy(tagAmount => tagAmount.Tag)
.Select(tagAmountGroup => new
{
Tag = tagAmountGroup.Key,
TotalAmount = tagAmountGroup.Sum(tagAmount => tagAmount.Amount)
}))
});
和输出是一样的;
Percentage Title Amount
53% Food 19
Hotel 5
Friends 5
Hotel 6 //Hotel should be grouped here and should with the value 11 :-(
Party 8
57% Family 17
Hotel 8
Mobile 8
Electricity 9
但是我想要的输出是:
Percentage Title Amount
53% Food 19
Hotel 11
Friends 5
Party 8
57% Family 17
Hotel 8
Mobile 8
Electricity 9
如您所见,我做了一切。但不是报告中分组的“酒店”。我究竟做错了什么?请指教!
我同意克里斯·卡明斯(Chris Cummings)关于分组错误应用的观察。因为你不压平(即调用SelectMany()
在TagsReport
现场,直到后你只有一个单一的项目,分组结果只有一个组的每个扁平序列卷起。
根据您所声明的期望输出,似乎您实际上确实有一个放错了的右括号。您应该这样写:
var ReportingData = ReportListQuery
.Where(Item => Item.Category == "expense")
.GroupBy(item => item.Title)
.Select(itemGroup => new
{
Percentage = Math.Round((itemGroup.Sum(item => item.Amount) / MonthExpense) * 100),
ExpenseTitle = itemGroup.Key,
ExpenseCalculation = itemGroup.Sum(item => item.Amount),
TotalTagAmounts = itemGroup
.SelectMany(item => item.TagsReport.Select(tag => new
{
Tag = tag,
Amount = item.Amount
})) // add parenthsis here
.GroupBy(tagAmount => tagAmount.Tag)
.Select(tagAmountGroup => new
{
Tag = tagAmountGroup.Key,
TotalAmount = tagAmountGroup.Sum(tagAmount => tagAmount.Amount)
}) // remove parenthesis here
});
换句话说:您希望将每个“按标题分组”组中的整个扁平化项目序列分组,而不是将每个组中的每个单个项目扁平化。我只是)
在倒数第二行上删除了第二个,并在第二个GroupBy()
呼叫之前添加了一个。
这将精确地产生您描述的输出。这仍然很奇怪(单个标签数量的总和超过每个标题组的总费用),但是至少这是您明确要求的。:)(好吧,不计算百分比……给定示例数据,就不可能有一个MonthExpense
将百分比相加的值,所以我只是不费力气试图使该数字正确显示)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句