How do I recover filters from a query?

Asked

Viewed 58 times

1

Hello. You can find out which filters, sorters, etc were used in a query?

Example:

public class Program
{
    class Produto
    {
        public int Id;
        public string Nome;

        public Produto(int id, string nome)
        {
            this.Id = id;
            this.Nome = nome;
        }
    }

    public static void Main()
    {
        List<Produto> produtos = new List<Produto>();
        produtos.Add(new Produto(1, "Arroz"));
        produtos.Add(new Produto(2, "Feijão"));
        produtos.Add(new Produto(3, "Trigo"));
        produtos.Add(new Produto(4, "Batata"));

        var query = from produto in produtos
                 where produto.Id < 3
                 select produto;
    }
}

In case, what I need is that query Return me that your filter is "id < 3"

1 answer

1

Yes, it is possible.

Thus:

var query = (from produto in produtos
             where produto.Id < 3).AsQueryable();
var predicado = query.Expression;
  • Thanks for the answer. I implemented this code, but I can’t extract anything else from Expression. It only provides me with the following methods: > Canreduce, Equals, Gethashcode, Gettype, Nodetype, Reduce, Reduceandcheck, Reduceextension and Tostring.

  • So working with the Expression deserves another question.

  • 1

    That’s not gonna work. produtos is a List<T>, and therefore, from x in produtos will be compiled as Enumerable.Select(produtos, x => ...). The method Enumerable.Select accepts a delegate, not an expression. Soon, the lambda expression will be converted to a delegate - and after that conversion it is impossible to recover the original Tree Expression.

Browser other questions tagged

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