c# - 有条件的分组、求和、相减

标签 c# entity-framework linq

具有以下对象列表:

public class Example
{
    public string Local { get; set; }
    public string Type { get; set; }
    public int Amount { get; set; }
}

我想按 Local 对列表进行分组并且在同一字段(总计)中,求和 Amount其中Type是“输入”并减去Amount其中Type是“输出”。

示例:

enter image description here

根据上面的示例,我想要以下结果:

enter image description here

我已经尝试了以下代码,但它不起作用。它在 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/

相关文章:

entity-framework - 为什么我会得到一个带有 Entity Framework 代码优先外键属性的额外外键列?

c# - 如何使用JSON.Net读取JSON并输出HTML?

c# - 通用数据库字段的数据类型是什么

java - 在 Unity 中使用自定义 list 文件和权限?

C# 用户控件 : access controls properties

c# - 如何在 VB.NET 中压缩文件/目录?

c# - 使用 linq 和 Entity Framework 创建适当的模型

c# - db.SaveChanges() 导致 System.Data.Entity.Infrastructure.DbUpdateException' 发生在 EntityFramework.dll 中

c# - 有没有办法结合 LINQ 和异步

C#:按可为空的 DateTime 属性对对象列表进行排序