Is it possible to make a condition within a Select?

Asked

Viewed 294 times

4

I’m performing a consultation using Select, to select only the required fields and consequently have higher performance.

In my View user can choose certain fields to be loaded

Man 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 error, but is there any way to do something similar ?

1 answer

6


Yeah, but not with the parole inside 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 the goal is performance, you’ll have to use the Dynamic LINQ Nuget package sort of like this:

String columns = "";
if (viewModel.CarregarNome) {
    columns += "Nome"
}
var entity = context.Clientes.AsNoTracking()
         .Select("new(" + columns + ")").ToList();
  • It depends on your return could have conditional so var return = Entity. Select(x => new { Name = viewModel.Loadable == true ? x.Name : String.Empty });

  • That’s actually a chuncho, and Nome is defined as such, without any performance gain.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.