Answers that use Enumerable.Repeat
have a potential problem: it creates a values replay, that is, if the object passed by parameter is a reference type ( a class, for example), copies of the reference to the object passed by parameter and not copies of the object will actually be made.
So all items in the list would be the same item . That is, if Compra
is a class, a single instance of Compra
will be created and the reference to this instance will be copied to each item in the list - changing one of the purchases, all changes.
If this is a problem for you, here is an alternative that actually creates X different instances.
Solution that works for both reference types and value types:
private List<Compra> CriarCompras(int numComprasParaGerar)
{
return (from i in new int[numComprasParaGerar] select new Compra()).ToList();
}
Or:
private List<Compra> CriarCompras(int numComprasParaGerar)
{
return new int[numComprasParaGerar].Select(i => new Compra()).ToList();
}
(I prefer the first option, I think more expressive).
Edit:
I agree on grade and gender with the @bigown edition that says the original AP code is the best option; not because of performance but because it is more expressive and everything in it reveals only the real intention without having to create for example an array that only serves as artifice to guarantee the iterations.
I would still add the number of purchases in the list builder and maybe it would be further: return an array instead of returning a list, returning in the method a IList<Compra>
or a IEnumerable<Compra>
(but also has to see the side of the consumer code - which is more convenient for him).
I would therefore use a code something like this:
private IList<Compra> CriarCompras(int qtdComprasParaGerar)
{
IList<Compra> compras = new Compra[qtdComprasParaGerar];
for (int i = 0; i < qtdComprasParaGerar; i++)
compras[i] = new Compra();
return compras;
}
So my option using LINQ is just to answer directly the question (which wants to dispense with the for statement) and to warn about using Enumerable.Repeat
.