In this post I will show a method using which we can create datetime ranges. This method is not specific to the datetime, instead it can be used with any type including int, long etc. There is a new method in .net framework 3.5 using which we can easyly create integer ranges. For example.
foreach(int i in Enumerable.Range(1,10))Console.Write(i);
However, in this post I will show how we can create integer ranges and datetime ranges with custom intervals etc.
How it works?
Let us first see how we will be using it.
foreach(DateTime d in CreateRange( DateTime.Now,DateTime.Now.AddDays(6),(x)=>x.AddDays(1)))Console.Write(d.ToLongDateString() );
result:
- Sunday, September 14, 2008
- Monday, September 15, 2008
- Tuesday, September 16, 2008
- Wednesday, September 17, 2008
- Thursday, September 18, 2008
- Friday, September 19, 2008
- Saturday, September 20, 2008
The action is happening inside the CreateRange<t>(t start,t end,Func<t,t> func) method. Here is the CreateRange() method.
CreateRange() method
public static IEnumerable<t> CreateRange<t>(t start, t end, Func<t,t> func) where t: IComparable{if(start.CompareTo(end)==-1){//End is greater than startfor(t i=start;(start.CompareTo(i) != 1) && (end.CompareTo(i) != -1); i=func(i))yield return i;}else {//end is less than or equal to startfor(t i=start; (start.CompareTo(i)!=-1) && (end.CompareTo(i)!= 1); i=func(i))yield return i;}}
Remarks
Here the CreateRange() method takes the start and the end values together with the function for incrementing/decrementing the range interval. The important thing is that the funtion provided to the CreateRange() method should perform the action of returning the next value in the range. Here is a sample which prints out all the odd numbers between 1 and 10.
foreach(int i in CreateRange(1,10, (x)=> ++x))Console.Write(i);
Few things to note:
- You can only create ranges for types which implements IComparable
- The start and end is included in the range, CreateRange(1,3,(x)=>++x) would include both 1 and 3/li>
- While creating numeric ranges, don't use (x)=>x++ ever, rather use (x)=>++x.
Happy coding!