具有以下对象列表:
public class Example
{
public string Local { get; set; }
public string Type { get; set; }
public int Amount { get; set; }
}
我想按 Local
对列表进行分组并且在同一字段(总计)中,求和 Amount
其中Type
是“输入”并减去Amount
其中Type
是“输出”。
示例:
根据上面的示例,我想要以下结果:
我已经尝试了以下代码,但它不起作用。它在 Total
上返回 NULL .
var Balances = Examples
.GroupBy(y => y.Local)
.Select(y => new BalanceDTO
{
Local = y.FirstOrDefault().Local
Total = y.Where(z => z.Type == "Input").Sum(z => z.Amount) - y.Where(z => z.Type == "Output").Sum(z => z.Amount)
}).ToList()
我应该做什么?
最佳答案
我已将计算属性添加到您的 Example
类中:
public class Example
{
public string Local { get; set; }
public string Type { get; set; }
public int Amount { get; set; }
public int NetAmount
{
get
{
return Type == "Input" ? Amount : -1 * Amount;
}
}
}
然后在您的 LINQ 中将它们分组到 Local
字段中,就像您所做的那样,然后我使用了 LINQ Aggregate method将每组中所有这些“净总数”相加:
var Balances = Examples
.GroupBy(y => y.Local)
.Select(y => new
{
Local = y.Key,
Total = y.Sum(y => y.NetAmount)
}).ToList();
关于c# - 有条件的分组、求和、相减,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60998943/