gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:06:21 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com