Is it possible to make a condition within a Select?

4

I'm running a query using Select , to select only the required fields and consequently to have higher performance.

In my View user can choose certain fields to load

My ViewModel

public class CliViewModel {
   public bool CarregarNome {get;set;}
}

and in my select

var entity = context.Clientes.AsNoTracking()
             .Select(cli => new { 
               if(viewModel.CarregarNome) {
                  x.Nome
               }
             }).ToList();

Of course this expression of the error, but is there any way to do something similar?

    
asked by anonymous 03.11.2015 / 18:18

1 answer

6

Yes, but not with the conditional within Select :

var entity = context.Clientes
                    .AsNoTracking()
                    .ToList();

if(viewModel.CarregarNome) 
{
    var retorno = entity.Select(x => new { x.Nome });
} else {
    var retorno = entity.Select(x => new { /* Descreva os atributos aqui */ });
}

If your goal is performance, you'll have to use the NuGet Dynamic LINQ package or less like this:

String columns = "";
if (viewModel.CarregarNome) {
    columns += "Nome"
}
var entity = context.Clientes.AsNoTracking()
         .Select("new(" + columns + ")").ToList();
    
03.11.2015 / 18:22