Reputation: 11990
I have an ASP.NET MVC application. Let's suppose that I have this view:
@model IEnumerable<MyClass>
.....
On the server side, I have a linq query, to my database, using EF:
public ActionResult Index()
{
var query = from t in context.MyClass
select t;
//now comes the question
return View(query);
return View(query.AsEnumerable()); //is there any difference?
}
I think that the AsEnumerable() is not necessary because the query will automatically cast to it, so, can someone explain me when the AsEnumerable() is useful?
Thank you!
Upvotes: 2
Views: 1113
Reputation: 53958
It is not necessary. The query you have declared results in a sequence, which implements the IEnumerable
interface.
As you will see here, the Select
extension method of types that implement the IEnumerable
, returns a IEnumerable
.
public static IEnumerable<TResult> Select<TSource, TResult>(
this IEnumerable<TSource> source,
Func<TSource, TResult> selector)
Your query
var query = from t in context.MyClass
select t;
will be compiled to
var query = context.MyClass.Select(x=>x);
hence I am refering to the Select
extension method.
Regarding now the use of AsEnumerable()
The AsEnumerable(IEnumerable) method has no effect other than to change the compile-time type of source from a type that implements IEnumerable to IEnumerable itself.
Also
AsEnumerable(IEnumerable) can be used to choose between query implementations when a sequence implements IEnumerable but also has a different set of public query methods available. For example, given a generic class Table that implements IEnumerable and has its own methods such as Where, Select, and SelectMany, a call to Where would invoke the public Where method of Table. A Table type that represents a database table could have a Where method that takes the predicate argument as an expression tree and converts the tree to SQL for remote execution. If remote execution is not desired, for example because the predicate invokes a local method, the AsEnumerable method can be used to hide the custom methods and instead make the standard query operators available.
For further documentation, please have a look here.
Upvotes: 1