我有一个列表dateHolder
,它具有DateTime数据类型并保存数百个DateTime值。该列表从最旧的值累积到最新值。这是一个功能:
private void CheckQuarter()
{
int lastPoint = dateHolder.Count(); //Has dates from 4/12/2015 to 30/11/2017
DateTime startDate = dateHolder(0); //startDate = 4/12/2015
DateTime endDate = dateHolder(lastPoint - 1); //endDate = 30/11/2017
}
从上面的代码示例中,我想根据仅限日期和月份检查某些日期的发生。我对年份价值不感兴趣。我想检查的日期和月份值是:
1st Jan
31st Mar
1st Apr
30th Jun
1st Jul
30th Sep
1st Oct
31st Dec
从上述日期和月份值中,您可能会看到我正在检查季度值。现在,在startDate
和endDate
内,如何查看我提到的那些日期?非常感谢...
答案 0 :(得分:0)
LINQ Enumerable.Count
您可以使用an overload that takes a predicate。例如如果你只关心月和日:
var yourTargetDates = new List<DateTime>()
{
new DateTime(1, 1, 1), // Jan 1st
new DateTime(1, 3, 31), // March 31st
... // etc
};
var occurrences = dateHolder.Count(d => yourTargetDates.Any(td => td.Month == d.Month && td.Day == d.Day));
你可能仍然需要在某些日期和时间周围迎合怪异,尽管在处理日期和时间时通常会这样。
答案 1 :(得分:0)
我找到了一种方法来实现它。这是功能:
private void CheckQuarter()
{
int lastPoint = dateHolder.Count();
DateTime startDate = dateHolder(0);
DateTime endDate = dateHolder(lastPoint - 1);
DateTime CurrD = startDate;
while ((CurrD <= endDate))
{
if ((CurrD.Month == 1 && CurrD.Day == 1)) //1st Jan
{
//Do your process
}
else if ((CurrD.Month == 3 && CurrD.Day == 31)) //31st Mar
{
//Do your process
}
else if ((CurrD.Month == 4 && CurrD.Day == 1)) //1st Apr
{
//Do your process
}
else if ((CurrD.Month == 6 && CurrD.Day == 30)) //30th Jun
{
//Do your process
}
else if ((CurrD.Month == 7 && CurrD.Day == 1)) //1st July
{
//Do your process
}
else if ((CurrD.Month == 9 && CurrD.Day == 30)) //30th Sep
{
//Do your process
}
else if ((CurrD.Month == 10 && CurrD.Day == 1)) //1st Oct
{
//Do your process
}
else if ((CurrD.Month == 12 && CurrD.Day == 31)) //31st Dec
{
//Do your process
}
else
{
//Do your process
}
CurrD = CurrD.AddDays(1);
}
}
这是实现目标的一种方法。但是,我认为有一种更简单的方法需要更少的编码才能做到这一点。