Create objects within a list without for/foreach C#


private List<Compra> CriarCompras(int numComprasParaGerar)
    List<Compra> lstCompras = new List<Compra>();
    for (int i = 0; i < numComprasParaGerar; i++)
       lstCompras.Add(new Compra());

    return lstCompras;

Following the example, is there any other way to create N objects within a list of the same type?


All the shapes in the answers work the same or similar. However, as mentioned by @Maniero there is a huge performance problem in all of them when compared to for .

Test performed by @Maniero on .NET Fiddle


Responses that 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 and not copies of the actual object.

So all the items in the list would be the same item . In other words: if Compra is a class, a single Compra instance will be created and the reference to this instance will be copied for each item in the list – changing one purchase changes all.

If this is an issue for you, I present below 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 yet:

private List<Compra> CriarCompras(int numComprasParaGerar)
    return new int[numComprasParaGerar].Select(i => new Compra()).ToList();

(I prefer the first option, I think it's more expressive).


I agree in degree and gender with the @Maniero edition which says 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, an array that only serves as a device to guarantee the iterations.

I would still add the number of purchases in the list constructor and maybe go even further: return an array instead of returning a list, returning in the method an IList<Compra> or an IEnumerable<Compra> (but then you have to see the side as well of 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 the question directly (which wants to dispense with the for statement) and to warn about using Enumerable.Repeat .

Scroll to Top