Reputation: 9856
I have a start date and an end date (in sql server datetime format). I want to split this into several ranges ie several pairs of start and end date values. NOTE - I have .NET 3.5 and Visual studio 2008.
Eg. S = 2005. E = 2010, Chunk size = 1 year. Paris generated = 2005-06, 06-07, 07-08, 08-2010
The chunks can be of any number of days/months. I put the code in an SO post, after my main method and I get some errors. Post - Split date range into date range chunks
Code -
public static IEnumerable<Tuple<DateTime, DateTime>> SplitDateRange(DateTime start, DateTime end, int dayChunkSize)
{
DateTime chunkEnd;
while ((chunkEnd = start.AddDays(dayChunkSize)) < end)
{
yield return Tuple.Create(start, chunkEnd);
start = chunkEnd;
}
yield return Tuple.Create(start, end);
}
I get two errors:
The body of 'CodeHere.csproj.ScriptMain.SplitDateRange(System.DateTime, System.DateTime, int)' cannot be an iterator block because 'IEnumerable
And:
The name 'Tuple' does not exist in the current context
Upvotes: 1
Views: 6359
Reputation: 2954
Here is a .NET 3.5 way of doing things. As others have said, Tuple didn't exist in .NET 3.5..
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
internal class Program
{
private static void Main(string[] args)
{
var myDateTime = new DateTime(2013, 10, 29);
var myEndDateTime = new DateTime(2014, 10, 29);
var result = SplitDateRange(myDateTime, myEndDateTime, 10);
var file = new System.IO.StreamWriter("c:\\dateFile.txt");
foreach (var item in result)
{
file.WriteLine("StartDate: {0}, EndDate: {1}", item.StartDateTime, item.EndDateTime);
}
file.Close();
}
public static IEnumerable<SplitDateTime> SplitDateRange(DateTime start, DateTime end, int dayChunkSize)
{
DateTime chunkEnd;
while ((chunkEnd = start.AddDays(dayChunkSize)) < end)
{
yield return new SplitDateTime(start, chunkEnd);
start = chunkEnd;
}
yield return new SplitDateTime(start, end);
}
}
public class SplitDateTime
{
public SplitDateTime(DateTime startDateTime, DateTime endDateTime)
{
StartDateTime = startDateTime;
EndDateTime = endDateTime;
}
public DateTime StartDateTime { get; set; }
public DateTime EndDateTime { get; set; }
}
}
Upvotes: 1
Reputation: 1500105
You're trying to use System.Tuple<T1, T2>
, which was only introduced in .NET 4. You're using .NET 3.5, so that structure isn't available. I suggest you create your own DateRange
type which encapsulates a start and end DateTime
, then return an IEnumerable<DateRange>
instead.
Either that, or upgrade to .NET 4 or 4.5...
Upvotes: 5