Ideal C# IEnumerable generic number sequence with start and interval -


i looking for, not find, idiomatic example generic class implementing ienumerable, this: constructor takes start , interval, , getenumerator returns ienumerator, starts starts , goes on forever returning items interval.

in other words, like:

public class sequence<t> : ienumerable<t> t :... {      public t start { get; private set; }     public t interval { get; private set; }      sequence(t start, t interval)      {         ...     }      ienumerator<t> getenumerator()      {         for(t n = start ; ; n += interval) // not compile             yield return n;      }      ... else? } 

there lots of related questions, , small snippets, bits&pieces, have not been able find single nice example of complete class, @ least similar enough. how implement this, if there existing class this, it'd know, not answer question.

so, actual question(s): recent c# version has introduced new features useful this, , ideal example code it?

also if there common pitfalls, mistakes inexperienced c# developers make related kind of class, know.


update: since exact thing i'm asking seems impossible, guess next best thing replacing interval lambda getting next item, or that.

thanks dlev suggesting func, using helper class.

public class sequence<t> : ienumerable<t> {   public t start { get; private set; }   public t interval { get; private set; }   private func<t, t, t> adder { get; set; }    public sequence(t start, t interval, func<t,t,t> adder)   {     start = start;     interval = interval;     adder = adder;   }    public ienumerator<t> getenumerator()   {     (t n = start; ; n = adder.invoke(n, interval))       yield return n;   }    ienumerator ienumerable.getenumerator()   {     return this.getenumerator();   } } 

you can use this:

int = 0; foreach (int t in new sequence<int>(3, 4, (int a, int b) => + b)) {     if (i == 10)     {         break;     }     i++;     console.writeline(t); } 

alternatively, require t implement sort of addable interface , call add method, think cleaner around.


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -