我有很多笔和很多历史,都有一列a,b,c。
我希望能够使用LINQ进行合并,并具有where条件(日期)。
public async Task<int> CountInPenLot(DateTimeOffset date)
{
var lotPens = await _context.LotPens.ToListAsync();
var lotHistory = await _context.LotHistories.ToListAsync();
// union lotpens and lot history on columns a,b,c where condition date
//continue my logic
}
答案 0 :(得分:2)
由于您只想对c
列中的值求和,所以最简单的方法是只运行两个查询并将它们加在一起。
public async Task<int> CountInPenLot(DateTimeOffset date)
{
var lotPensSum = await _context.LotPens
.Where(x => x.DateColumn == date) //Filter on the date
.SumAsync(x => x.c); //Sum up column c
var lotHistorySum = await _context.LotHistories
.Where(x => x.DateColumn == date)
.SumAsync(x => x.c);
return lotPensSum + lotHistorySum;
}
答案 1 :(得分:0)
我不确定C列的数据类型。如果它不是数字,那么您需要修改代码以检查空值并强制转换类型,然后对其求和。
public async Task<int> CountInPenLot(DateTimeOffset date)
{
int total = 0;
var lotPensSum = await _context.LotPens
.Where(x => x.DateColumn == date).toList(); //Filter on the date
var lotHistorySum = await _context.LotHistories
.Where(x => x.DateColumn == date).toList();
foreach (var lotPens in lotPensSum)
{
if (lotPens.c != null)
{
int intC = 0;
int.TryParse(lotPens.c, out intC);
total += intC;
}
}
foreach (var lotHistor in lotHistorySum )
{
if (lotHistor.c != null)
{
int intC = 0;
int.TryParse(lotHistor.c, out intC);
total += intC;
}
}
return total;
}