Dynamic query in a List

Posted on

Question :

How to apply a filter on a generic List object using Lambda?

I know that with Reflection I can get an array with the names of the properties of my object and through Reflection itself retrieve the property of the object from its name but I do not know how to pass this array and compare the values of the properties within Lambda.


Answer :

The intent of performing a dynamic query in List was to assemble a form that would display the List in a DataGridView and query all attributes of List objects, and the List inside the form could contain any object. The solution presented by Mateus proved to be viable, but when I presented it to the rest of the team we found some problems among them:

  • When an object has another object as an attribute;
  • You would not be able to customize the query, eg limit the fields the attributes to use.

Once I hit the head with the team for 2 hours I opted for the following approach: An interface called “IListaAuxiliar” with a method called “FilterList” that will be implemented by all classes that use the query form. This one by your will also have an attribute of the same interface. So when calling the form we pass the object (Application_BLL for example) and call the method FilterList without parameters to get the complete list. Then save the search term entered by the user and filter again. Calls to the FilterList method are not cumulative because they act on an unchanged list stored inside the FlexList object. Below is the code for the interface and object.

public class Aplicacao : Objeto_DTL
    private int _ID;
    public int ID
        get { return _ID; }
        set { _ID = value; }

    private string _Nome;
    public string Nome
        get { return _Nome; }
        set { _Nome = value; }

    private List<Versao> _versao;
    public List<Versao> Versao
        get { return _versao; }
        set { _versao = value; }

public interface IListaAuxiliar
    List<Object> FiltrarLista(string valor);

public class Aplicacao_BLL : IListaAuxiliar
    private List<Aplicacao> _lista;

    public List<Object> FiltrarLista(string valor)
        var lTemp = _lista.Cast<Object>().Where(
                x => (x as Aplicacao).ID.Value.ToString().Contains(valor)
                    || (x as Aplicacao).Nome.Value.ToString().Contains(valor)
                    || (x as Aplicacao).Descricao.Value.ToString().Contains(valor)
                    || (x as Aplicacao).Criacao.Value.ToString().Contains(valor)

        return lTemp.ToList();


I made a small adaptation of How to: Use Expression Trees to Build Dynamic Queries (C # and Visual Basic ).

To make it easier to understand, I’ll create the Cliente class.

public class Cliente {

    public string Nome { get; set;}
    public int RG { get; set;}
    public int CPF { get; set;}

    public Cliente () : this ("", 0, 0) { }

    public Cliente(string nome, int rg, int cpf) {
        this.Nome = nome;
        this.RG = rg;
        this.CPF = cpf;

    public override string ToString() {
        return Nome + "t" + RG + "t" + CPF + "n";


Once you’ve created your clients, I’ll filter back those with Name equal to Mario or have the 100 , done this I will sort them by RG , the expression would look like this:

clientes.Where(cliente => cliente.Nome == "Mario" || cliente.CPF == 100)
        .OrderBy(cliente => cliente.RG)

To create it dynamically, you can do it this way:

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;

class Program
    static void Main()
        // cria os clientes
        Cliente cliente1 = new Cliente("Mario", 963, 222);
        Cliente cliente2 = new Cliente("Carlos", 183, 444);
        Cliente cliente3 = new Cliente("Pedro", 722, 666);
        Cliente cliente4 = new Cliente("Mario", 737, 888);
        Cliente cliente5 = new Cliente("Maria", 159, 100);
        Cliente cliente6 = new Cliente("Carla", 194, 240);
        Cliente cliente7 = new Cliente("Mario", 10, 19);

        // adiciona os clientes em uma lista
        List<Cliente> listClientes = new List<Cliente>();

        // recupera o IQueryable da lista de clientes
        IQueryable<Cliente> queryableData = listClientes.AsQueryable<Cliente>();

        // cria o parâmetro a ser utilizado na consulta
        ParameterExpression pe = Expression.Parameter(typeof(Cliente), "cliente");

        // expressão 'cliente.Nome == "Mario"'
        Expression column = Expression.Property(pe, typeof(Cliente).GetProperty("Nome"));
        Expression value = Expression.Constant("Mario");
        Expression expr = Expression.Equal(column, value);

        // expressão 'cliente.CPF == 100'
        column = Expression.Property(pe, typeof(Cliente).GetProperty("CPF"));
        value = Expression.Constant(100, typeof(int));
        Expression expr2 = Expression.Equal(column, value);

        // expressão '(cliente.Nome == "Mario" || cliente.CPF == 100)'
        Expression predicateBody = Expression.OrElse(expr, expr2);

        // expressão 'queryableData.Where(cliente => 
        // (cliente.Nome == "Mario" || cliente.CPF == 100))'
        MethodCallExpression whereCallExpression = Expression.Call(
            new Type[] { queryableData.ElementType },
            Expression.Lambda<Func<Cliente, bool>>(predicateBody, 
                                                   new ParameterExpression[] { pe }));

        // expressão 'cliente.RG'
        Expression expr3 = Expression.Property(pe, typeof(Cliente).GetProperty("RG")); 

        // expressão 'whereCallExpression.OrderBy(cliente => cliente.RG)'
        MethodCallExpression orderByCallExpression = Expression.Call(
            new Type[] { queryableData.ElementType, typeof(int) },
            Expression.Lambda<Func<Cliente, int>>(expr3, new ParameterExpression[] { pe }));

        // cria e executa a query
        IQueryable<Cliente> results = queryableData.Provider

        // imprime resultado
        foreach (Cliente cliente in results)


The result is:

Nome    RG      CPF
Mario   10      19
Maria   159     100
Mario   737     888
Mario   963     222

You can also create a generic method:

public static IQueryable<T> Find<T>(List<T> list, string column, object value, 
                                    string columnOrder)
    // recupera o IQueryable da lista
    IQueryable<T> queryable = list.AsQueryable<T>();

    // cria o parâmetro a ser utilizado na consulta
    ParameterExpression pe = Expression.Parameter(typeof(T), "param");

    // expressão 'param.column == value'
    Expression columnExp = Expression.Property(pe, typeof(T).GetProperty(column));
    Expression valueExp = Expression.Constant(value);
    Expression expr = Expression.Equal(columnExp, valueExp);

    // expressão 'queryable.Where(param => param.column == value)'
    MethodCallExpression whereCallExpression = Expression.Call(
        new Type[] { queryable.ElementType },
        Expression.Lambda<Func<T, bool>>(expr, new ParameterExpression[] { pe }));

    // expressão 'param.columnOrder'
    Expression expr2 = Expression.Property(pe, typeof(T).GetProperty(columnOrder));

    // expressão 'whereCallExpression.OrderBy(param => param.columnOrder)'
    MethodCallExpression orderByCallExpression = Expression.Call(
        new Type[] { queryable.ElementType, expr2.Type },
        Expression.Lambda(expr2, new ParameterExpression[] { pe }));

    // cria e executa a query
    IQueryable<T> results = queryable.Provider.CreateQuery<T>(orderByCallExpression);

    return results;

To use it, enter the parameters as shown below:

IQueryable<Cliente> results = Find(listClientes, "Nome", "Mario", "CPF");

Resulting in:

Nome    RG  CPF
Mario   10  19
Mario   963 222
Mario   737 888

If you need to access more object attributes or call some method, you can do this:

// exemplo base, considerando que a classe Cliente possui o atributo Endereco,
// que por sua vez possui o atributo Logradouro, teríamos algo assim:
// param.Endereco.Logradouro.ToLower() == "avenida paulista"
// que pode ser feito conforme mostrado abaixo


// cria o parâmetro a ser utilizado na consulta
ParameterExpression pe = Expression.Parameter(typeof(Cliente), "param");

// expressão 'param.Endereco'
Expression columnEndereco = Expression.Property(pe, typeof(Cliente).GetProperty("Endereco"));
// expres

Leave a Reply

Your email address will not be published. Required fields are marked *