LINQ with condition in where using variable

8

I have the following table:

USUARIO

Nome      | Idade
João      | 21
Maria     | 18

I want to make only one query that returns all users, or only returns users of a specific age based on a C # variable.

Also by name.

int idade = 18;
string nome = "";

var resultado = (from u in db.Usuario
                 // Se idade != 0 considerar o where.
                 // Caso contrário, trazer todos os usuarios.
                 where u.Nome == nome && u.Idade == idade).ToList();

How could I do this?

I'm using Entity Framework.

    
asked by anonymous 26.08.2015 / 22:01

3 answers

6

Unless the question is poorly explained, it does not seem to be a problem with LINQ, it's normal code:

int idade = 18;
string nome = "";

if (idade != 0) {
    var resultado = (from u in db.Usuario
            where u.Nome == nome && u.Idade == idade).ToList();
} else {
    var resultado = db.Usuario.ToList();
}

Note that you are only doing one query, it does not perform two. If you want to insist on this:

var resultado = (from u in db.Usuario
        where idade == 0 || (u.Nome == nome && u.Idade == idade)).ToList()

In this case there will be extra processing cost in the condition in each evaluated element. It is not something that will make a lot of difference in small volumes, but it can do in large volumes. I'd opt for the other way. Whenever possible, it is better to draw a loop.

    
26.08.2015 / 22:07
2

Simple boolean logic

var users = from u in db.Usuario
            where idade == 0 || (u.Idade == idade && u.Nome == nome)
    
26.08.2015 / 22:05
0

Jedaias, if you have a dynamic or complex condition, it may be best to use a method syntax instead of the expression syntax.

Let's say you have two optional filters, in case name or age, you could do this:

var usuarios = db.Usuario;
if (idade != 0) 
{
    usuarios = usuarios.Where(usuario => usuario.Idade == idade);
}
if (!String.IsNullOrWhiteSpace(nome)) 
{
    usuarios = usuarios.Where(usuario => usuario.Nome.contains(nome));
}
var resultado = usuarios.ToList();
    
31.08.2015 / 16:54