如果查询中的Amount
和Id
匹配,如何减去FreeUpOriginId
?我可以使用foreach
达到我想要的结果,但是我想知道是否可以在一个选择查询中完成。
DateTime DateToday = DateTime.Now;
var availed = (from c in db.Allocations
where c.Status == Status.Availed && c.FiscalYear == DateToday.Year
select c).ToList();
var freeup = (from c in db.Allocations
where c.Status == Status.FreeUp && c.FiscalYear == DateToday.Year
select c).ToList();
foreach (var availedItem in availed)
{
foreach (var freeupItem in freeup)
{
if (availedItem.Id == freeupItem.FreeUpOriginId)
{
availedItem.Amount = availedItem.Amount - freeupItem.Amount;
}
}
}
return new JsonNetResult() { Data = availed };
答案 0 :(得分:0)
是的,有一个最简单的代码,这是指向您的方向的基本代码段:
var Result = availed.Select(x => new Data()
{
//your properties
Amount = x.Amount - freeupItem.FirstOrDefault(u => u.Id == x.Id)?.Amount ?? 0
}).ToList();
答案 1 :(得分:0)
LINQ是一种查询语言。它不允许您更新查询中的属性。您必须创建新对象(按照Barr J的回答),或者最终需要做等效的foreach
。通常,foreach
更具可读性。
尝试一下:
var allocs = db.Allocations.Where(x => x.FiscalYear == DateToday.Year);
var query =
from avail in allocs.Where(x => x.Status == Status.Availed)
join free in allocs.Where(x => x.Status == Status.FreeUp)
on avail.Id equals free.FreeUpOriginId
select new { avail, free };
query.ToList().ForEach(x => x.avail.Amount -= x.free.Amount);
最后一个赞可以写为:
foreach (var x in query)
{
x.avail.Amount -= x.free.Amount;
}