IQueryable methods are not resolved for dynamic query variable
I'm trying to figure out how to use dynamic variable开发者_运维技巧s for my methods that use LINQ queries. For example, that 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 doesn't 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();
}
The error is: 'object' does not contain a definition for 'Count'. How can I get it working with dynamic keyword?
You'd have to use:
gridUsers.VirtualItemCount = Queryable.Count(query);
gridUsers.DataSource = Enumerable.ToList(query);
Dynamic typing doesn't "do" extension methods. (I'm not completely sure why. The compiler stashes a fair amount of information about the call site - it would have to store all the using
directives associated with the call site too, basically. It would also slow down dynamic binding, which may be the problem they're trying to avoid. Maybe it was just too much work for too little benefit.)
EDIT: Just out of interest, why are you trying to use dynamic typing for your sequence in the first place? I suspect you'll find all kinds of things like this become trickier... LINQ depends quite heavily on various bits of type inference.
Note that having an IQueryable<dynamic>
or an IEnumerable<dynamic>
is fine, and will work rather better.
精彩评论