Return true if the list contains multiple bands of consecutive months

I am working with C# listone that has a type DateTimethat has several lines of data in a format dd/mm/yyyy, and I'm trying to compute a method that returns trueif one of the following three conditions is C# listtrue : T23>

  • If all elements of the list are equal, i.e. Equal months and years that are simple
  • If the month and year are in sequence.

Example:

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

The above example Month and Yearis in sequence, so the method returns true.

3. If the list contains several bands of months in a sequence

Example:

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;

, , ?

+4
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;
+1

All Articles