LINQ with Where condition using variable

Asked

Viewed 1,242 times

8

I have the following table:

USUARIO

Nome      | Idade
João      | 21
Maria     | 18

I want to do in only one consultation return all users, or return only users of 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 that?

I’m using Entity Framework.

3 answers

6


Unless the question is poorly explained it seems to me not to be a problem with LINQ, it is 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()

I put in the Github for future reference.

In this case there will be extra processing cost on condition in each assessed element. It is not something that will make a lot of difference in small volumes, but it can make in large volumes. I would opt for the other way. Whenever possible it is best to take a processing out of a loop.

  • Perfect! The first option I had already thought about, but is that my query is actually much bigger and different in the posted question. Actually the second option will help me keep the code clean. It lacked logical thinking on my part.

  • 1

    It’s a matter of opinion, in mine clean code is the first. Even if you have other things to add. I actually think with more things, it’s more important to do it that way.

2

Simple Boolean logic

var users = from u in db.Usuario
            where idade == 0 || (u.Idade == idade && u.Nome == nome)
  • Perfect! What was really lacking was logic on my part......

  • @Jedaiasrodrigues Of course not :) I agree with him that an if/Else is more suitable and makes it easier to read the code. Non-trivial boolean conditions hide the intent of the code.

0

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

say you have two optional filters, in the case name or age, could do so:

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();

Browser other questions tagged

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