I am having problem while using AsQueryable
, I found some example in which casting i.e. AsQueryable required for this extension and in some example directly as AsQueryable(). I check both case with Stopwatch and concluded with almost same result for multiple investigation.
Lets take example:
//With AsQueryable()
var studentId = dbContext.Students.AsQueryable().Where(a=>a.Name == "Abc").Select(a=>a.Id).FirstOrDefault();
//With AsQueryable<Student>()
var studentId = dbContext.Students.AsQueryable<Student>().Where(a=>a.Name == "Abc").Select(a=>a.Id).FirstOrDefault();
What is difference between using AsQueryable()
and AsQueryable<type>()
and which is efficient?
When you call AsQueryable()
without specifying generic parameter type it's inferred by compiler from an object you call it at.
var source = new List<int>();
var queryable = source.AsQueryable(); // returns IQueryable<int>
is equivalent to
var queryable = source.AsQueryable<int>();
Update
To answer question asked in comments:
Then what is the use for having two different way? Is there any particular situation when we have to use only one of it?
Yes, you can't specify type parameter explicitly when using anonymous types, because you don't have class name:
source.Select((x,i) => new { Value = x, Index = i }).AsQueryable();
And that's exactly why type inference was introduced: to let you call generic methods without specifying type parameters when using anonymous types. But because it works not only with anonymous types, and saves you unnecessary typing, it's very common to rely on type inference whenever it's possible. That's why you'll probably see AsQueryable()
without type parameter most of the times.