我有两个表,我想结合生成一个报告
我使用此代码加入表
db.tblProcessorLists.GroupJoin(
db.tbltransactions,
a => a.UserID,
b => b.UserID,
(x, y) => new
{
Processor = x,
Data = y.ToList()
}
)
.Select(a => new Report
{
Processor = a.Processor,
TotalTrans = a.Data
}).ToList();
这就是输出
我想在我的报告类中插入数据。
这可能吗?怎么样?
编辑我已经尝试了这个,但它不起作用
db.tblProcessorLists.GroupJoin(
db.tbltransactions,
a => a.UserID,
b => b.UserID,
(x, y) => new
{
Processor = x,
Data = y.ToList()
}
)
.Select(a => new Report
{
Processor = a.Processor,
SummaryTransaction = a.Data.Select(x=>new Summaryreport{ month=x.month, year=x.year, total=x.totaltransaction})
}).ToList();
虽然你没有指定,但我认为你想要的是总结一个月的所有数据。所以代替:
Processor Month Value
1 2018-1 2
1 2018-1 3 => sum all 2018-1 values of processor 1: 2+3=5
1 2018-2 4
1 2018-2 5 => sum all 2018-2 values of processor 1: 4+5=9
2 2018-1 1
2 2018-1 2 => sum all 2018-1 values of processor 2: 1+2=3
您所要做的就是更改GroupJoin中的ResultSelector,以便将所有数据分组到具有相同[年,月]的组中。结果是[年,月,和]这一年和月的所有值]
看看Enumerable.GroupBy的一个重载
var result = db.tblProcessorLists.GroupJoin( // GroupJoin processors and transactions
db.tbltransactions,
processor => processor.UserID, // from every processor take the UserId
transaction => transaction.UserID, // from every transaction take the UserId
// ResultSelector: use eacht processor with its zero or more matching transactions
// to make one new object
(processor, transactionsOfThisProcessor) => new
{
Processor = processor,
// group all transactionsOfThisProcessor into groups with same [year, month]
// and sum the values of all transactions in each group
TransactionTotals = transactionsOfThisProcessor
.GroupBy(transaction => new
{
Year = transaction.Year, // KeySelector: make groups with
Month = transaction.Month // same [year, month]
},
// element selector: Transaction.Value
transaction => transaction.Value,
// ResultSelector: key = [year, month],
// elements are all values of this [year, month] group
// sum all values
(key, valuesWithThisYearMonth) => new
{
Year = key.Year,
Month = key.Month,
Total = valuesWithThisYearMonth.Sum(),
}),
});