Scroll List DTO in C #

2

I have the following code in c #:

List<Usuario> ret = new List<Usuario>();
UsuarioRepositorio repositorio = new UsuarioRepositorio(); 
var dtos = repositorio.Seleccionar(); 
foreach(dtos) 
{ 

    ret.Add(dtos); 
} 

return ret;

As you can see, I have a List called ret and dtos is a List DTO that receives the values of the Seleccionar() method. But I would like to know how to travel or map data to store it in ret, and then return it.

    
asked by Alberto Atencio 18.04.2018 в 18:34
source

5 answers

1

If you want to map the properties of a data to a user and then add it to your user list:

foreach(var dto in dtos)
{
    //Creo el usuario que vamos a añadir en ret
    Usuario user = new Usuario();

    //Meto las propiedades del dto recorrido en el usuario
    user.propiedad1 = dto.propiedad1;
    user.propiedad2 = dto.propiedad2;
    ....

    //Añado el usuario
    ret.Add(user);
}

return ret;
    
answered by 18.04.2018 / 19:22
source
1

using System.Collections.Generic

List<Usuario> resultado = new List<Usuario>();
dtos.ForEach(dto => {
    var r = new Usuario();
    r.Nombre = dto.Nombre;
    resultado.Add(r);
});

Although if it's just for mapping, I recommend you look AutoMapper

Greetings,

    
answered by 19.04.2018 в 13:50
1

Thank you very much everyone, your comments were very helpful, it is already resolved:

public List<Usuario> Seleccionar()
{
     List<Usuario> ret = new List<Usuario>();
     UsuarioRepositorio repositorio = new UsuarioRepositorio();
     var dtos = repositorio.Seleccionar();
     foreach (var dto in dtos)
     {
         ret.Add(UsuarioAdaptador.ConvertirAEntidad(dto));
     }
     return ret;                        
}
    
answered by 19.04.2018 в 16:02
0

What you have to put in the foreach is an element to handle during the iteration.

foreach(var dato in dtos) // Por cada "dato" en la lista de datos "dtos".
{
    ret.Add(dato);
}

For that matter, every time the foreach finds an element in dtos it will "select" that element and it will reference it in the var iable "data" and it will treat it within that block .

    
answered by 18.04.2018 в 19:26
0
List<Usuario> ret = new List<Usuario>();
UsuarioRepositorio repositorio = new UsuarioRepositorio(); 
var dtos = repositorio.Seleccionar(); 


return dtos.ToList();
    
answered by 19.04.2018 в 13:34