IQueryable methods not allowed for dynamic query variable

I am trying to figure out how to use dynamic variables for my methods that use LINQ queries. For example, this works fine:

using (DBDataContext db = new DBDataContext()) { var query = from c in db.Users select new { c.Firstname, c.Lastname, c.Age }; gridUsers.VirtualItemCount = query.Count(); gridUsers.DataSource = query.ToList(); } 

But this does not work:

 using (DBDataContext db = new DBDataContext()) { dynamic query = from c in db.Users select new { c.Firstname, c.Lastname, c.Age }; gridUsers.VirtualItemCount = query.Count(); gridUsers.DataSource = query.ToList(); } 

Error: "object" does not contain a definition for "Count". How can I make it work with a dynamic keyword?

+4
source share
1 answer

You will need to use:

 gridUsers.VirtualItemCount = Queryable.Count(query); gridUsers.DataSource = Enumerable.ToList(query); 

Dynamic typing does not do extension methods. (I'm not quite sure why. The compiler writes quite a lot of information about the call site - in general, it will have to store all the using directives associated with the call site, and it also slows down dynamic linking, which can be a problem they are trying to avoid. Maybe it was too much work for too little good.)

EDIT: Just out of interest, why are you trying to use dynamic typing for your sequence in the first place? I suspect you will find all things like this getting harder ... LINQ is highly dependent on various bits of type of output.

Note that having an IQueryable<dynamic> or IEnumerable<dynamic> is fine and will work better.

+10
source

Source: https://habr.com/ru/post/1342253/


All Articles