LINQ Anonimous Type as parameter

2

I am trying to create a method that receives an anonymous type (see LINQ)
(Please correct me if the term tipo anônimo (anonymous types) is incorrect)

MinhaLista (produtos.Select(p => new {p.Id, p.Estoque})

I asked Visual Studio to create the method automatically and it was generated: public static object MinhaLista (object @select)

I would like the method to be possible:

foreach (var produto in produtos)
            {
                Debug.WriteLine(produto.Id);
            }

What is the correct way to define a method to receive this tipo anônimo (anonymous types) ?

    
asked by anonymous 06.01.2016 / 02:14

3 answers

3

I suggest you create a Extension Method from object for this, since it guaranteed the reuse, it follows the code of the extension method:

public static class ObjectExtensions
{
    public static object GetPropriedade(this object obj, string propName)
    {
        if (obj== null)
            return null;
        PropertyInfo prop = obj.GetType().GetProperty(propName);
        if (prop != null)
           return prop.GetValue(obj, null);
        return null;
    }
}

Then just call the object that owns the property:

public void MostrarPropriedade(object obj)
{
    Console.WriteLine(obj.GetPropriedade("Id"));
}

You can see an example in my Fiddle: link

    
06.01.2016 / 04:13
1

In general it is not a good idea to try passing an anonymous type between methods.

The ideal in this case is you create a new type to use, such as

public class MeuProduto
{
    public int Id { get; set; }
    public int Estoque{ get; set; }
}

So you could change your query to use this type

MinhaLista (produtos.Select(p => new MeuProduto{Id = p.Id, Estoque = p.Estoque})

After that you should be able to declare your function as

public static object MinhaLista (IEnumerable<MeuProduto> @select)
    
06.01.2016 / 12:40
0

Another way I found was by using IEnumerable<dynamic> (but the ability to intellisense for attributes is lost)

{
   MinhaLista (produtos.Select(p => new {p.Id, p.Estoque})
}

public static object MinhaLista (IEnumerable<dynamic> produtos)
{
    foreach (var produto in produtos)
    {
        Console.WriteLine(produto.Id);
    }
    ....
}
    
06.01.2016 / 13:20