c# – LINQ with condition in where using variable

Question:

I have the following table:

USUARIO

Nome      | Idade
João      | 21
Maria     | 18

I want to do just one query that returns all users, or returns only 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 am using Entity Framework.

Answer:

Unless the question is poorly explained it doesn't 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 it's only doing one query, it doesn't do two. If you want to insist on it:

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

I put it on GitHub for future reference .

In this case there will be extra processing cost in the condition in each element evaluated. It's not something that will make much of a difference on small volumes, but it can do on large volumes. I would choose the other way. Whenever possible it is better to take a loop out of processing.

Scroll to Top