In fact, it's a problem. Since I've never used anything so I do not know if it has a better solution than the ones below.
You can create a class to receive this new type created by this query , hence you would return List<Resultado>
if this class calls Resultado
.
This is because the way you are creating an anonymous type to receive the result, then you do not know what type it is until the execution.
It does not have to be a class itself. You can create a tuples with the composition of this type , it could use something like List<Tuple<tipoID, tipoTIPO, tipoID>>
. C # 7 has tuple in the language and its use is usually more interesting.
You can declare this explicitly as a list and access the fields as list elements. It only works if all fields are of the same type. Of course you can use List<object>
to accept any type but it loses the type guarantee.
Finally you can return to consider that the return of your function is List<object>
, after all the anonymous type created is certainly a object
. It loses strong typing but it is a solution. You can still return List<dynamic>
but I doubt it is best to return object
.
I'll use the example on this page to show what happens to the result and what types we're talking about:
using System.Console;
using System.Linq;
using System.Collections.Generic;
class Customer {
public int ID { get; set; }
public string Name { get; set; }
}
class Order {
public int ID { get; set; }
public string Product { get; set; }
}
public static class Program {
public static void Main() {
// Example customers.
var customers = new Customer[] {
new Customer{ID = 5, Name = "Sam"},
new Customer{ID = 6, Name = "Dave"},
new Customer{ID = 7, Name = "Julia"},
new Customer{ID = 8, Name = "Sue"}
};
// Example orders.
var orders = new Order[] {
new Order{ID = 5, Product = "Book"},
new Order{ID = 6, Product = "Game"},
new Order{ID = 7, Product = "Computer"},
new Order{ID = 8, Product = "Shirt"}
};
// Join on the ID properties.
var query = from c in customers
join o in orders on c.ID equals o.ID
select new { c.Name, o.Product };
WriteLine(query.GetType());
// Display joined groups.
foreach (var group in query) {
WriteLine("{0} bought {1}", group.Name, group.Product);
}
var lista = query.ToList();
WriteLine(lista.GetType());
//criando explicitamente uma lista de string (neste caso é possível)
var query2 = from c in customers
join o in orders on c.ID equals o.ID
select new List<string> { c.Name, o.Product };
WriteLine(query2.GetType());
foreach (var group in query2) {
WriteLine("{0} bought {1}", group[0], group[1]);
}
var lista2 = query2.ToList();
WriteLine(lista2.GetType());
}
}
See working on dotNetFiddle .
Example using an explicit class . It conforms to what I said.
I emphasize that there may be a better solution but my lack of experience prevents me from stating. If I remember something I update here.