Thursday, 8 August 2013

Range enumerable with delegate movenext/increase

Range enumerable with delegate movenext/increase

I'm trying to print dates starting 2013 1 1 ending 2015 1 1 exclusive.
The problem is MoveNext is called before current so it starts printing at
2013 2 1. My question is 1) Is there some type of Range class that already
exist in .NET? I only know of enumerable.range which isn't close to what I
need. 2) Is using a bool hasStarted and checking it in MoveNext the most
idiomatic to fix my problem?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DateTest
{
class Program
{
static void Main(string[] args)
{
foreach (var m in Range.Create(new DateTime(2013, 1, 1), new
DateTime(2015, 1, 1), s => s.AddMonths(1)))
Console.WriteLine(m);
}
}
static class Range { public static Range<T> Create<T>(T s, T e,
Func<T, T> inc) where T : IComparable<T> { return new Range<T>(s, e,
inc); } }
class Range<T> : IEnumerable<T>, IEnumerator<T> where T : IComparable<T>
{
T start, pos, end;
Func<T,T> inc;
public Range(T s, T e, Func<T,T> inc) { pos=start= s; end = e;
this.inc = inc; }
public T Current
{
get { return pos; }
}
public void Dispose()
{
//throw new NotImplementedException();
}
object System.Collections.IEnumerator.Current
{
get { return pos; }
}
public bool MoveNext()
{
pos = inc(pos);
return pos.CompareTo(end) < 0;
}
public void Reset()
{
pos = start;
}
public IEnumerator<T> GetEnumerator()
{
return this;
}
System.Collections.IEnumerator
System.Collections.IEnumerable.GetEnumerator()
{
return this;
}
}
}

No comments:

Post a Comment