微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 如果列表包含多个连续月份条带,则返回true

@H_404_2@
我正在使用一个类型为DateTime的C#列表,它有几行dd / mm / yyyy格式的数据,我试图找出一个方法,如果以下三个条件之一为真,则返回true

>如果所有列表项都相同,即.相同的月份和年份很简单
>如果按月和按年顺序排列.

例:

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

在上面,Month和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;

有没有类似的方法来检查第三个条件?

@H_404_2@

解决方法

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

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;
@H_404_2@ @H_404_2@
@H_404_2@
@H_404_2@

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐