Saturday, January 8, 2011

Different way to loop through a list of number in C#

As I work more and more in a TDD or almost TDD way, I strive to write more concise and clear unit tests. For what ever reason i find the first way to loop clearer to read and faster to type.
 foreach(var i in Range(16)) {
 
     l.Measures.Current.Tracks[0].Steps[i].Set(100);
 }
 
 for(int i=0; i<16; i++) {
 
     l.Measures.Current.Tracks[0].Steps[i].Set(100);
 }
    
 Here is how to loop with an increment of 2.

 foreach (var i in Range(16, 2)){
 
     l.Measures.Current.Tracks[0].Steps[i].Set(100);
 }
Here is the function Range (v 1)
///   
 /// Return a list of integer from 0 to max-1  
 ///   
 /// The maximum number of integer to return ///   
 public  IEnumerable  Range(int  max)
 {
     return  Range(max, 1);
 }
 ///   
 /// Return a list of integer from 0 to max-1 with an increment  
 ///   
 /// The maximum number of integer to return /// The increment ///   
 public  IEnumerable  Range(int  max, int  increment)
 {
     return  Range(0, max, increment);
 }
 ///  
 /// Return a list of integer from start to max-1 with an increment  
 ///  
 /// The start value /// The max value /// the increment ///  
 public  IEnumerable  Range(int  start, int  max, int  increment)
 {
     int  i = start;
     while  (i < max)
     {
         yield  return  i;
         i += increment;
     }
 }

No comments:

Post a Comment