我有一个数据集(汽车):
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},
};
输出
关于c# - LINQ - 分组依据,然后有条件地求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54732364/