Matthew Watson
Matthew Watson

Reputation: 109567

Linq method for creating a sequence of separate objects?

I must be reinventing the wheel here - but I've searched and I can't find anything quite the same...

Here's my code for creating a sequence of zero or more objects that have a default constructor:

public static IEnumerable<T> CreateSequence<T>(int n) where T: new()
{
    for (int i = 0; i < n; ++i)
    {
        yield return new T();
    }
}

My question is quite simple: Is there a Linq equivalent of this I should be using?

Upvotes: 5

Views: 207

Answers (2)

Botz3000
Botz3000

Reputation: 39610

Try this:

Enumerable.Range(1,count).Select(_ => new T());

Enumerable.Range will give you the current number from the specified range as parameter, but you can simply ignore that (named as _ in the example).

Upvotes: 8

raznagul
raznagul

Reputation: 375

Yes there is: var items = Enumerable.Repeat(new YourClass(), 10);

Upvotes: 0

Related Questions