如何从Linq中的相同列表中减去金额

时间:2018-08-20 07:19:47

标签: entity-framework linq

如果查询中的AmountId匹配,如何减去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 };

2 个答案:

答案 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;
}