Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing object of anonymous type as parameter to a method

I need do something like this:

public class carros 
{
    public int id { get; set; }
    public string nome { get; set; }
}

public void listar_carros()
{
    List<carros> cars = new List<carros>();
    cars.Add(new carros{ id= 1, nome = "Fusca" });
    cars.Add(new carros{ id= 2, nome = "Gol" });
    cars.Add(new carros{ id= 3, nome = "Fiesta" });

    var queryResult = from q in cars 
                      where q.nome.ToLower().Contains("eco") 
                      orderby q.nome 
                      select new { q.nome, q.id };

    doSomething(queryResult)
}

I need to pass the queryResult variable to function doSomething(). I tried use a dynamic type, List<T> object, but nothing works

public void doSomething(???? queryResult)
{
    foreach (carros ca in queryResult)
    {
        Response.Write(ca.nome);
        Response.Write(" - ");
        Response.Write(ca.id);
    }
}
like image 386
Felipe Maricato Moura Avatar asked Aug 19 '13 21:08

Felipe Maricato Moura


People also ask

What is the use of anonymous object?

Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first. The type name is generated by the compiler and is not available at the source code level. The type of each property is inferred by the compiler.


Video Answer


1 Answers

In general, it's almost always a bad idea to pass anonymous types between methods.

You should make a custom type to hold the nome and id values, then construct it instead of an anonymous type.


In your case, you already have a class that would work: carros. You can just implement your query to create it instead:

var queryResult = from q in cars 
  where q.nome.ToLower().Contains("eco") 
  orderby q.nome 
  select new carros {q.nome, q.id};

Your method would then be:

public void doSomething(IEnumerable<carros> queryResults)
like image 123
Reed Copsey Avatar answered Oct 12 '22 00:10

Reed Copsey