How can I use linq to initialize an array of repeated elements?

Posted by Eric on Stack Overflow See other posts from Stack Overflow or by Eric
Published on 2012-11-25T16:34:28Z Indexed on 2012/11/25 17:04 UTC
Read the original article Hit count: 235

Filed under:
|

At present, I'm using something like this to build a list of 10 objects:

myList = (from _ in Enumerable.Range(0, 9) select new MyObject {...}).toList()

This is based off my python background, where I'd write:

myList = [MyObject(...) for _ in range(10)]

Note that I want my list to contain 10 instances of my object, not the same instance 10 times.

Is this still a sensible way to do things in C#? Is there a cost to doing it this way over a simple for loop?

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ