Home > database >  Using IEnumerable.Repeat to populate a counter
Using IEnumerable.Repeat to populate a counter

Time:02-17

I want to create an IEnumerable list using Enumerable.Repeat and would like the set the Id of the objects to the nth element of the list as per the code below. Is this possible with Enumerable.Repeat or would I need to do something different?

var stuff = Enumerable.Repeat("This is element <n>", 50);

So the resulting output from the following code ...

foreach (var s in stuff)
{
   Console.WriteLine(s);
}

...would be ...

This is element 0
This is element 2
This is element 3
...
This is element 49

CodePudding user response:

Usually I use Enumerable.Range for such tasks:

var stuff = Enumerable.Range(0, 50)
    .Select(i => new thing {id = i})

It is not possible to achieve this task with Repeat cause it does exactly what it "promises" - repeats exactly the same element multiple times:

class thing{public int id;}
var counter = 0;
var stuff = Enumerable.Repeat(new thing { id = 1 }, 50)
    .ToArray();
Console.WriteLine(object.ReferenceEquals(stuff[0], stuff[1])); // prints "True"
  • Related