Working with anonymous type

1

I have the following code snippet:

var filter = new { categoria = 1, cond2 = foo, ... };
p = new ProdutoBusiness().listarProdutos( filter ).ToList();

I wanted to work with this anonymous type as a parameter to filter, but I do not know how to get this type of value in the referenced method:

public IEnumerable<Produto> listarProdutos( tipo???? filter = null) {

My intention is to change the query according to what comes in the filter. For example:

if(filter != null){
   if(filter.categoria != ""){
     query = from P in con.produto
             join C in con.categoria on P.categoriaID equals C.categoriaID
             where P.ativo == true
             && P.categoriaID == filter.categoria
             orderby P.nome ascending
             select P;
   }
   [...]
 }

Any ideas / suggestions?

/ ************* /

If someone has the same question with these ' dynamic ' types mentioned in the answer, I have resolved this:

Popular the object:

var filter = new { categoria = 1, cond2 = foo, ... }

Receiving the parameter:

public IEnumerable<Produto> listarProdutos( dynamic filter = null) {}

Getting the 'key' value:

var fCategoria = filter.GetType( ).GetProperty( "categoria" ).GetValue( filter, null );
    
asked by anonymous 12.12.2016 / 21:07

1 answer

1

As the exact enumerable type is not known a solution is to tell the compiler that it should not check the typing and let the runtime resolve it. It is done with dynamic . Something like this:

public IEnumerable<Produto> listarProdutos(dynamic filter = null) {

But if you know it will always be this structure and it seems to know, then create a normal named type and use it instead of the anonymous type. The anonymous type is a facility when its structure does not matter much to what it needs. Eventually you can even reuse an existing type. Maybe you really want to:

public IEnumerable<Produto> listarProdutos(Filter filter = null) {

And would have:

public class Filter  {
    public int categoria = 1;
    public ALgumTipoAqui cond2 = foo,
    ...
}

In C # 7 you will have even better ways.

But depending on your specific need you may have another solution, perhaps quite different from what you are thinking right now.

    
12.12.2016 / 22:13