The answers they use Enumerable.Repeat
have a potential problem: it creates a repeat of values, 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 will be made, not copies of the actual object.
So that all items in the list would be the same item. That is: if Compra
is a class, a single instance of Compra
and the reference to this instance will be copied for each item in the list - changing one of the purchases, all changes.
If this is a problem for you, I present below an alternative that actually creates X different instances.
Solution that works so much for Reference types how much to value types:
private List<Compra> CriarCompras(int numComprasParaGerar)
{
return (from i in new int[numComprasParaGerar] select new Compra()).ToList();
}
Or else:
private List<Compra> CriarCompras(int numComprasParaGerar)
{
return new int[numComprasParaGerar].Select(i => new Compra()).ToList();
}
(I prefer the first option, I find more expressive).
Edit:
I agree in degree and gender with the @Maniero edition that says that the original AP code is the best option; not for performance but because it is more expressive and everything in it reveals only the real intention without having to create for example a array which only serves as a ruse to ensure iterations.
I would still add the number of purchases in the list constructor and perhaps go further: return an array instead of returning a list, returning in the one method IList<Compra>
or a IEnumerable<Compra>
(but it also has to do with the consumer code - which is more comfortable for it).
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;
}
Therefore, my option using LINQ is only to answer directly the question (who wants to dispense with the statement of the for) and to warn about the use of Enumerable.Repeat
.
The answers they use
Enumerable.Repeat
have a problem: it creates a repeat of values, that is, the reference to the object passed by parameter. So that all items in the list will be the same item. That is, a single instance ofCompra
and the reference to this instance will be copied for each item in the list - changing one of the purchases, all changes.– Caffé