c# - 如何选择按月分组的行
问题描述
如何选择按月分组的行。
所以我有一个实体:
public class Security
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Quatation { get; set; }
public SecurityType SecurityType { get; set; }
public double Denomination { get; set; }
public CurrencyType DemoniationType { get; set; }
public virtual ICollection<ReportPeriod> ReportPeriods { get; set; }
}
报告期实体:
public class ReportPeriod
{
public Guid Id { get; set; }
public DateTime Start { get; set; }
public DateTime End { get; set; }
public Guid SecurityId { get; set; }
public Guid StockExchangeId { get; set; }
public double Amount { get; set; }
public virtual Security Security { get; set; }
}
所以我需要以某种方式在一年中的每个月为 ReportPeriod 获取一般金额。有没有人有一些想法如何做到这一点?
解决方案
你想要一般的月份金额。
- 假设您希望它采用月份第一个日期的格式(我们在
Dictionary<DateTime, double>
哪个Key
月份有一般金额Value
)。 - 假设,范围
start
和end
不跨越整个月。
在您的课程中添加此属性Security
。
public Dictionary<DateTime, double> AmountGroupedByMonth
{
get
{
Dictionary<DateTime, double> table = new Dictionary<DateTime, double>();
if (ReportPeriods != null && ReportPeriods.Count > 0)
{
ReportPeriod frtReportPeriod = ReportPeriods.First();
DateTime monthStDt =
new DateTime(frtReportPeriod.Start.Year, frtReportPeriod.Start.Month, 1);
double groupedAmount = 0;
foreach (ReportPeriod reportPeriod in ReportPeriods)
{
//Checking if this report should be grouped with pervious report or not
if (monthStDt.Year == reportPeriod.Start.Year
&& monthStDt.Month == reportPeriod.Start.Month)
{
groupedAmount += reportPeriod.Amount;
}
else
{
//if we find that this report is of different month.
table.Add(monthStDt, groupedAmount);
groupedAmount = reportPeriod.Amount;
monthStDt =
new DateTime(reportPeriod.Start.Year, reportPeriod.Start.Month, 1);
}
}
if (groupedAmount != 0 && !table.ContainsKey(monthStDt))
table.Add(monthStDt, groupedAmount);
}
return table;
}
}
通过添加此属性,按月分组的数据将可轻松用于Security
. 而且,由于它没有存储在任何变量中,因此您无需在使用它之前对其进行更新(或生成)。只需调用此属性,它将使用最新的可用数据按月计算一般金额。
Security s = new Security();
DateTime nowDate = DateTime.Now;
s.ReportPeriods = new List<ReportPeriod>();
for(int i = 0; i <= 70; i = i + 5)
{
s.ReportPeriods.Add(new ReportPeriod(nowDate.AddDays(i), nowDate.AddDays( i + 3), 200 ));
}
Dictionary<DateTime, double> AmountGroupedByMonth = s.AmountGroupedByMonth;
输出将如下所示:
推荐阅读
- c# - 命名空间“Microsoft.Reporting”中不存在类型或命名空间名称“WebForms”(您是否缺少程序集引用?)
- bash - 在 ffmpeg 流上添加图像
- c# - 安装后 Outlook 插件未显示在 Outlook 菜单中
- python - ImportError:无法导入名称“PyDotnet”
- web - Chromium - chrome中的“由于用户没有先与文档交互而失败”?
- mysql - 使用条件调用多列的 SQL 查询(带 NA)
- c# - C# winform 应用程序运行时的 CRUD ConnectionStrings
- c# - Simple.OData.Client 真的很慢
- php - 如何 php lint 仅在 gitlab 中存在和修改文件?
- android - 在 WebView 中存储和使用 Cookie