加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 22:07:11 所属栏目:百科 来源:网络整理
导读:我正在使用一个类型为DateTime的C#列表,它有几行dd / mm / yyyy格式的数据,我试图找出一个方法,如果以下三个条件之一为真,则返回true 如果所有列表项都相同,即.相同的月份和年份很简单 如果按月和按年顺序排列. 例: 10/4/2016 10/3/2016 10/2/2016 10/1/201
我正在使用一个类型为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;

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

解决方法

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

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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读