Anonymous types and generics

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 create

public class ExtArrayStore<T> : IViewComponent 
{
    public IQueryable<T> Data { get; set; }

... // 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 get:

Type arguments for the ArrayStoreGenerator.CreateInstance (System.Linq.IQueryable) method cannot be taken out of use. Try explicitly specifying type arguments

Is there any way to achieve this? (I'm thinking of interfaces and returning an interface, but not sure if this will work) can anyone help with passing anon types to generics.

+5
source share
4 answers

usersQueryis entered as non-generic IQueryablebecause you explicitly state this in the variable declaration.

var usersQuery = .... IQueryable<TAnon>, ArrayStoreGenerator.CreateInstance.

+6

userQuery var.

+3

What if you try to use a local variable var usersQueryinstead of explicitly specifying its type?

+2
source

Try with ToArray:

var x = ArrayStoreGenerator.CreateInstance(usersQuery.ToArray());
0
source

All Articles