What's the best way to create a list with an arbitrary number of instances of the same object? i.e is there a more compact or efficient way to do the following?
static List<MyObj> MyObjs = Enumerable.Range(0, 100)
.Select(i => new MyObj())
.ToList();
(Enumerable.Repeat
would give me ten references to the same object, so I don't think it would work.)
Edited to reflect that this method does not work.
I was curious about your comment about Enumerable.Repeat
, so I tried it.
//do not use!
List<object> myList = Enumerable.Repeat(new object(), 100).ToList();
I confirmed that they do all share the same reference like the OP mentioned.
This wouldn't be hard to implement as an iterator:
IEnumerable<T> CreateItems<T> (int count) where T : new() {
return CreateItems(count, () => new T());
}
IEnumerable<T> CreateItems<T> (int count, Func<T> creator) {
for (int i = 0; i < count; i++) {
yield return creator();
}
}
Apparently, the answer is "no". Thanks, everyone!
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