c# - LINQ - 分组依据,然后有条件地求和

标签 c# linq

我有一个数据集(汽车):

Brand     DateSold    Amount  Bought/Sold
Toyota    06/07/2015  18.5    Bought
BMW       01/01/2016  25.15   Sold
Mercedes  06/06/2016  20.75   Bought  

我想按年份分组并返回金额总和,即:

Year Amount  
2015 -18.5   
2016 4.4

并将其输出到列表框中。

我可以在没有买入/卖出条件的情况下求和:

var AmountsByYear = cars.GroupBy(i => i.Date.Year)
                        .Select(g => new { 
                            Year = g.Key,
                            Total = g.Sum(i => i.Amount)
                        }).ToList();
lstAmountsByYear.DataSource = AmountsByYear;

最佳答案

由于您没有详细说明如何在您的数据结构中定义“买入/卖出”字段,我建议您使用枚举。例如,

public class Car
{
    public string Brand;
    public DateTime Date;
    public double Amount;
    public BusinessType BusinessType;
}

public enum BusinessType
{
    Bought = -1,
    Sold = 1
}

这将使您能够使用您的查询,如下所示进行最少的更改以获得预期的结果。

var AmountsByYear = cars.GroupBy(i => i.Date.Year)
                    .Select(g => new { 
                        Year = g.Key,
                        Total = g.Sum(i => i.Amount*(int)i.BusinessType)
                    }).ToList();

输入数据,

var cars = new List<Car>
{
    new Car{Brand="Toyota", Date = new DateTime(2015,06,07),Amount=18.5,BusinessType=BusinessType.Bought},
    new Car{Brand="BMW", Date = new DateTime(2016,01,01),Amount=25.15,BusinessType=BusinessType.Sold},
    new Car{Brand="Mercedes", Date = new DateTime(2016,06,06),Amount=20.75,BusinessType=BusinessType.Bought},
};

输出

enter image description here

关于c# - LINQ - 分组依据,然后有条件地求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54732364/

相关文章:

c# - C# 中锁定(或进入/退出)的最佳实践

c# - Automapper 使用简单注入(inject)器 (Ioc) 将依赖项注入(inject)自定义类型转换器

c# - 为 Linq Select 语句创建一个匿名对象

vb.net - Linq-to-Entities 聚合在外部函数中计算的列

c# - 如何返回 Dictionary<int, object>?

c# - Xamarin Forms Prism 调用方法

c# - 如何在 selenium C# 中获取 reCaptcha 图像

c# - 列表<T>的属性

ASP.net 缓存访问导致 foreach 循环中的 Collection Modified 异常

linq - 我用什么来获取所有值而不是firstordefault