One of the extension methods on IEnumerable<T> is .AsEnumerable(). This method converts the enumerable object it was called on into an instance of IEnumerable<T>. However, since an object must implement IEnumerable<T> in order to apply to this extension method, converting to IEnumerable<T> is a simple matter of casting to IEnumerable<T>. My question is why does this method exist at all?
Example:
List<string> strings = new List<string>() { "test", "test2", "test3" };
IEnumerable<string> stringsEnum1 = strings.AsEnumerable();
IEnumerable<string> stringsEnum2 = (IEnumerable<string>)strings;
In the example above, stringsEnum1 and stringsEnum2 are equivalent. What’s the point of the extension method?
As a corollary, why is there an .AsQueryable() method when casting to IQueryable<T> is equivalent?
Readability is the main issue here. Consider that
is far more readable than
Or imagine wanting to execute part of the query on the SQL Server and the rest in memory:
versus
Now, as for why such a method is useful at all think of the example of a
Tablein a LINQ to SQLDataContext. AsTableis anIQueryableit implementsIEnumerable. When you invoke aWheremethod on such aTableand enumerate through the results, code is executed that eventually causes a SQL statement to be executed on a SQL Server. WhatAsEnumerabledoes is says, no, I don’t want to use the LINQ to SQL provider to execute theWhere, I want to use the LINQ to Objects implementation ofWhere.Thus enumerating over
causes a query to be executed on a SQL Server whereas enumerating over
brings the table represented by
Tableinto memory and executes theWherefunctionality in memory (and not on the SQL Server!)This is the point of
AsEnumerable: to allow you to hide a specific implementation ofIEnumerablemethods and instead use the standard implementation.