filling list with foreach c sharp and .net

0

I have the following code in which I add items to a list by foreach this is my code:

var archivosguardados = new List<Archivos>();
foreach (var a in modelArchivo)
                {
                    FactoryClass.ArchivoModelToArchivo(_bd, a, ref archivo);
                    archivosguardados.Add(archivo);

                }

                _bd.Archivos.AddRange(archivosguardados);
                _bd.SaveChanges();

It happens that archivosguardados after going through the foreach has two elements but these are repeated, and since modelArchivo already verify that it is passing the list correctly.

    
asked by Angelica Luna 19.04.2018 в 23:36
source

1 answer

1

In the code I see that when invoking ArchivoModelToArchivo() you use a parameter like ref , but I do not see where you hold the variable archivo , remember that if you use values by reference they point to the same address in memory, So you will step on the previous values.

Try defining the variable locally at foreach to see how it works

foreach (var a in modelArchivo)
{
    Archivos archivo;
    FactoryClass.ArchivoModelToArchivo(_bd, a, ref archivo);

    archivosguardados.Add(archivo);
}

Another tip, when you have method like these, parameters are not used by reference, but the function returns the value as an answer

public Archivos ArchivoModelToArchivo(xxTipo _bd, xxTipo a)
{
    // aqui codigo

    return archivo;
}

then you would use it

foreach (var a in modelArchivo)
{
    var archivo = FactoryClass.ArchivoModelToArchivo(_bd, a);

    archivosguardados.Add(archivo);
}

as you'll see it looks much better

    
answered by 20.04.2018 / 06:24
source