Reputation: 6019
I cannot find a way to pass an anonymous type to a generic class as a type parameter.
// this is the class I want to instantiate
public class ExtArrayStore<T> : IViewComponent
{
public IQueryable<T> Data { get; set; }
... // the creator class
public static class ArrayStoreGenerator
{
public static ExtArrayStore<T> CreateInstance<T>(IQueryable<T> query)
{
return new ExtArrayStore<T>();
}
}
// trying to use this
IQueryable usersQuery= ((from k in bo.usersselect new { userid = k.userid, k.username}).AsQueryable());
var x = ArrayStoreGenerator.CreateInstance(usersQuery);
I am getting;
The type arguments for method ArrayStoreGenerator.CreateInstance(System.Linq.IQueryable)' cannot be inferred from the usage. Try specifying the type arguments explicitly
Is there a way to achieve this? ( I am thinking of Interfaces and returning an interface, but not sure if it would work) can any one help with passing anon types to generics.
Upvotes: 5
Views: 1356
Reputation: 45445
usersQuery
is being typed as the non-generic IQueryable
because you explicitly specify that in the variable's declaration.
Instead, do var usersQuery = ...
. This will type the variable as IQueryable<TAnon>
, which then matches the signature of ArrayStoreGenerator.CreateInstance
.
Upvotes: 6
Reputation: 29632
Try with ToArray
:
var x = ArrayStoreGenerator.CreateInstance(usersQuery.ToArray());
Upvotes: 0
Reputation: 16032
What if you try var usersQuery
local variable instead of explicitly specify its type?
Upvotes: 2