Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq method for creating a sequence of separate objects?

Tags:

c#

linq

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?

like image 244
Matthew Watson Avatar asked Mar 27 '12 08:03

Matthew Watson


1 Answers

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).

like image 129
Botz3000 Avatar answered Nov 14 '22 23:11

Botz3000