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?
You can use Enumerable.Range
instead:
int count = 10;
List<MyObject> objects = Enumerable.Range(0, count)
.Select(i => new MyObject { Iteration = i })
.ToList();
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With