Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current iteration of the Enumerable.Repeat method

Having this code:

   return Enumerable.Repeat<MyClass>(new MyObject
   {   
     Iteration = // Get the current loop index 
   },
   10).ToList<MyClass>();

   public MyClass
   {
     public int Iteration {get;set;}
   }

How can I set the current loop index in the property Iteration by using the Enumerable.Repeat method?

like image 991
anmarti Avatar asked Oct 01 '13 15:10

anmarti


2 Answers

You can use Enumerable.Range instead:

int count = 10;
List<MyObject> objects =  Enumerable.Range(0, count)
     .Select(i => new MyObject { Iteration = i })
     .ToList();
like image 200
Tim Schmelter Avatar answered Oct 25 '22 14:10

Tim Schmelter


If you want to get the ordinal of the current item, one way is to use the Select overload that exposes an index. You can then create something like an anonymous type to hold the contents of the original enumerable (in this case, your Repeat result) and the index:

var repeats = Enumerable.Repeat("Something", 10).Select((s, i) => new { s, i });

foreach (var rep in repeats)
    Console.WriteLine(rep.i + rep.s);

Prints:

0Something
1Something
...
9Something

I'm not sure what you'd need this for. If it's just to create a list of objects, then Tim's alternative would be better suited (though in theory this would also work).

like image 44
Adam Houldsworth Avatar answered Oct 25 '22 14:10

Adam Houldsworth