Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

Whenever possible, the compiler can do type inference for you: http://msdn.microsoft.com/en-us/library/twcad0zb.aspx

And in that case, there's no difference, advantage, or penalty either way. Type inference just makes your life easier and your code shorter.

However, I've run into cases when consuming APIs where a type implements several interfaces, e.g.

IEnumerable<IMySimpleThing>, IEnumerable<IMyComplexThing>, IEnumerable<MyComplexThing>

and type inference isn't sufficient if you're trying to get at a specific interface, e.g.

IEnumerable<MyComplexThing>

So in that case, specifying type to the generic, like .AsQueryable<MyComplexThing>(), will do the trick.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top