Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IQueryable C# Select

this is my code... but i need select only column to display in my Datagridview. I Need the code to select only some columns.. example

Select{t => t.usu_Login, t => t.usu_Login}

public List<tb_usuario> Get(FilterDefinition filter)
{

     var contexto = new indNET_Entities();

     IQueryable<tb_usuario> Consulta = contexto.tb_usuario.AsQueryable<tb_usuario>()
                                                        .Where(t => t.usu_Ativo == 1)
                                                        .OrderBy(t => t.usu_Login);


     return Consulta.ToList();

}
like image 589
MrZerocaL Avatar asked Jan 20 '12 04:01

MrZerocaL


1 Answers

If you only want a limited number of columns and you intend to pass the result out of the method, first declare a concrete type to describe the elements.

public class UsuarioData
{
     public string UsuLogin { get; set; } // or whatever
     public string UsuName { get; set; }  // or whatever
}

Then you can use this in the return type for the method

public List<UsuarioData> Get(...) 

And finally, use the type in your select.

var consulta = contexto.tb_usuario.Where(whatever).OrderBy(whatever)
                   .Select(t => new UsuarioData
                                {
                                     UsuLogin = t.usu_login,
                                     UsuName = t.usu_name
                                }
                           );

return consulta.ToList();

And, of course, your callers should expect to get this as the result (or just use type inference with var).

like image 147
Anthony Pegram Avatar answered Oct 16 '22 04:10

Anthony Pegram