如果列表具有多个连续月份条带,则返回true

时间:2014-08-19 17:19:23

标签: c# list datetime

我正在使用类型C# list DateTime的{​​{1}},它有dd/mm/yyyy格式的多行数据,我正在尝试找一个返回true的方法以下三个条件之一是true

  1. 如果所有列表项都相同,即。简单的等月和年
  2. 如果按月和按年顺序。
  3. 示例:

    10/4/2016  
    10/3/2016   
    10/2/2016   
    10/1/2016   
    10/12/2015
    

    在上文中,Month and Year按顺序排列,因此方法返回true

    3。如果列表按顺序有多个月份

    示例:

    10/2/2016   
    10/1/2016   
    10/12/2015
    10/2/2016   
    10/1/2016   
    10/12/2015
    10/2/2016   
    10/1/2016   
    10/12/2015
    

    在上面的列表中,它有三个连续月份12/2015,1/2016,2/2016。因此,对于上面的列表,它应该返回true。它应该返回false,即使一个月不按顺序

    我能够使用以下方法编写第二个条件的方法,其中dd / yyyy应该是顺序的

    for (var x = 1; x < terms.Count; ++x)
        {
            var d1 = terms[x - 1];
            var d2 = terms[x];
    
    
            if (d2.Year == d1.Year)
            {
                if ((d1.Month - d2.Month) != 1) return false;
                continue;
            }                              
    
            if ((d1.Year - d2.Year) != 1) return false;
            if (d1.Month != 1 || d2.Month != 12) return false;
        }
        return true;
    

    有没有类似的方法可以检查第三种情况?

1 个答案:

答案 0 :(得分:1)

我不会使用月份和年份,但考虑增加时间。

DateTime currentDateTime;
foreach(var d in terms)
{
  if(currentDateTime == default(DateTime))
  {
    currentDateTime = d;
  }
  else
  {
    currentDateTime = currentDateTime.AddMonths(1);
    if(currentDateTime != d) return false;
  }
}
return true;

重复相同的序列(这次是伪代码):

// Determine initial sequence
while(currentDateTime.AddMonths(1) == nextDateTime) count++;

// Make sure that the whole sequence is a multiple of the short sequence
if(totalLength % count != 0) return false;

// Check remaining sequences
for(iteration in 1 .. totalLength / count)
  for(index in 1 .. count)
    if(terms[index] != terms[count * iteration + index]) return false;

// No elements differed
return true;