[英]how to get running total by month
我正在嘗試填充圖形,我的模型看起來像這樣
public class Transaction : BaseEntity
{
public TransactionType TransactionType { get; set; }
public DateTime TransactionDate { get; set; }
public double TransactionAmount { get; set; }
}
public enum TransactionType{
Deposit = 0,
Withdraw = 1
}
我用 2018 年前 2 個月的樣本數據填充了這個模型。
b.HasData(new
{
Id = Guid.NewGuid().ToString(),
AccountId = "37846734-172e-4149-8cec-6f43d1eb3f60",
TransactionAmount = 3334.38,
TransactionDate = new DateTime(DateTime.UtcNow.AddYears(-2).Year, 1, 20),
TransactionType = TransactionType.Deposit
});
b.HasData(new
{
Id = Guid.NewGuid().ToString(),
AccountId = "37846734-172e-4149-8cec-6f43d1eb3f60",
TransactionAmount = -3334.38,
TransactionDate = new DateTime(DateTime.UtcNow.AddYears(-2).Year, 1, 21),
TransactionType = TransactionType.Withdraw
});
b.HasData(new
{
Id = Guid.NewGuid().ToString(),
AccountId = "37846734-172e-4149-8cec-6f43d1eb3f60",
TransactionAmount = 1000.23,
TransactionDate = new DateTime(DateTime.UtcNow.AddYears(-2).Year, 1, 25),
TransactionType = TransactionType.Deposit
});
b.HasData(new
{
Id = Guid.NewGuid().ToString(),
AccountId = "37846734-172e-4149-8cec-6f43d1eb3f60",
TransactionAmount = 1008.18,
TransactionDate = new DateTime(DateTime.UtcNow.AddYears(-2).Year, 4, 10),
TransactionType = TransactionType.Deposit
});
b.HasData(new
{
Id = Guid.NewGuid().ToString(),
AccountId = "37846734-172e-4149-8cec-6f43d1eb3f60",
TransactionAmount = -34.10,
TransactionDate = new DateTime(DateTime.UtcNow.AddYears(-2).Year, 4, 19),
TransactionType = TransactionType.Withdraw
});
我試圖得到一個結果,即每個月末的余額是多少。
例如在
2018 年 1 月 1000.23
4 月 1974.23(1 月為 1000.23 + 4 月為 974.0)
但我得到的是
1 月 1000.23
四月 974.0
基本上它是單獨添加每個月的所有值。
var data = from t in transactions
group t by new { t.TransactionDate.Year, t.TransactionDate.Month } into g
select new
{
//Balance = g.Select(i =>
//{
// currentTotal += g.Sum(x => x.TransactionAmount);
// return new
// {
// //Date = i.TransactionDate,
// //Amount = i.TransactionAmount,
// currentTotal
// };
//}),
Balance = g.Sum(x => x.TransactionAmount),
g.First().TransactionDate.Month,
g.First().TransactionDate.Year
};
var yearlyGroups = data.OrderBy(x => x.Month).GroupBy(x => x.Year);
var lastTwoYearsSortedByMonth = yearlyGroups.OrderBy(x => x.Key).TakeLast(2);
正如您在上面的代碼中看到的,我嘗試了一些方法來獲得運行總數。 但不工作。
我想我的建議誤導了你。 我.Aggregate()
一個足夠優雅的解決方案來使用.Aggregate()
。
var runningBalance = 0.0;
var data = transactions.GroupBy(t => new { t.TransactionDate.Year, t.TransactionDate.Month })
.OrderBy(d => d.Key.Year)
.ThenBy(dd => dd.Key.Month)
.Select((g) => new
{
Year = g.Key.Year,
Month = g.Key.Month,
Balance = g.Sum(i => i.TransactionAmount),
RunningBalance = (runningBalance = (runningBalance + g.Sum(i => i.TransactionAmount)))
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.