Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a list filled with new instances of an object

Tags:

c#

list

linq

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

like image 597
Arithmomaniac Avatar asked Jul 25 '13 17:07

Arithmomaniac


3 Answers

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.

like image 166
Gray Avatar answered Sep 21 '22 04:09

Gray


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();
    }
}
like image 9
Josh Avatar answered Sep 21 '22 04:09

Josh


Apparently, the answer is "no". Thanks, everyone!

like image 4
Arithmomaniac Avatar answered Sep 20 '22 04:09

Arithmomaniac