score:7
in most cases, asenumerable().asqueryable()
is probably what you want, because:
- by doing an explicit
asenumerable()
, you're not running the risk of the underlying implementation makingasqueryable()
into a no-op, thereby ruining your attempt to close the query. i'm not saying that today's ef makesasqueryable()
a no-op (as far as i can tell, it doesn't), only that the behavior-- either no-op or transparently call asenumerable()-- isn't documented so relying on it isn't safe. asenumerable()
, unliketolist()
, doesn't load your entire resultset in memory in order to query it. this matters a lot with large resultsets. it's theoretically possible that for smaller resultsets, there could be some advantage to using tolist() (e.g. an optimized tolist() implementation pulls data in big chunks from the underlying provider, while enumeration involves more context switching) but that seems unlikely and hard to depend on across providers and versions, while the large-resultset advantage of asenumerable() will live forever.
the one case where i do like calling tolist()
is when i explicitly do want to force a query to execute right now. for example, if i want to catch errors in a query earlier in a method so that i can simplify error handling later, or i want to validate all the underlying data before continuing with the rest of the query. or if the query is more easily tested when chopped in two. and i'll never do this, unless i know that my recordset is going to be small, since calling tolist() on a multi-million-row query will kill your ram.
to answer your other question, converting data types in the linq documentation on msdn details which linq methods force query execution. according to that page, toarray()
, todictionary()
, tolist()
, and tolookup()
all force query execution.
asenumerable(), by contrast, doesn't force immediate query execution, but does "close" the query (using your term here, not sure if there's an official term for this). per http://msdn.microsoft.com/en-us/library/bb335435.aspx:
the asenumerable method can be used to hide the custom methods and instead make the standard query operators available.
in other words, running asenumerable will force all calls like take()
and where()
to use the generic linq implementations and not anythign custom which would cause a re-compile.
score:1
which methods can be used to "close" a compiled query.
methods that return a sequence use deferred execution, unless the method is something like toxyz
. where
, select
, take
, skip
, groupby
and orderby
etc falls under this. methods that return a single object forces execution of query, like first
, single
, tolist
and toarray
, todictionary
, tolookup
, any
, all
etc. see this excellent thread for more: linq - what is the quickest way to find out deferred execution or not?
i know most people use either .asenumerable() or .tolist(), but which other methods work as well? can i use .asqueryable(), or is this a no-op?
they all are different. justin has a grand explanation. you might also want to see: what's the difference(s) between .tolist(), .asenumerable(), asqueryable()? which has a good answer.
in general, you can understand the semantics of a method by seeing the name of the method itself. a method named assomething
implies it does nothing but returns the input as something. that may or may not involve returning a new object, but a reference is somehow maintained. for instance, alist<t>.asenumerable()
merely does a cast to ienumerable<t>
(of course it has bigger meaning in linq context). you can cast it back to list<t>
and mutate it reflecting the change everywhere. to test it:
var list = new list<int> { 1, 2 };
var enum = list.asenumerable();
var newlist = enum as list<string>;
newlist.add(3);
//print enum.count() -> 3
while methods that look like tosomething
, you get a totally new object often transformed to something else.
var list = new list<int> { 1, 2 };
var newlist = list.tolist();
newlist.add(3);
//print list.count -> 2
let's consider something outside the context of linq. object.tostring()
results in new string representation (strings are anyway immutable so thats a bit pointless). an interesting semantics is that of list<t>.asreadonly
which returns a new readonlycollection<t>
instance, but mutating the list outside of it changes the internal list of readonlycollection<t>
too, hence the naming asreadonly
.
var list = new list<int> { 1, 2 };
var readonlylist = list.asreadonly();
list.add(3);
//print readonlylist.count -> 3
Source: stackoverflow.com
Related Query
- Which methods to close a compiled query
- Can I use a compiled query as a source in a second query?
- NHibernate LINQ query performance, which code fragment is better?
- How to break complex query into different methods to achieve less code complexity
- Can I cite a Compiled Query as the Data Source to a Compiled Query?
- Extension methods syntax vs query syntax
- Nested "from" LINQ query expressed with extension methods
- Could not find an implementation of the query pattern for source type 'System.Data.Entity.DbSet'
- LINQ query to perform a projection, skipping or wrapping exceptions where source throws on IEnumerable.GetNext()
- What is the difference between LINQ query expressions and extension methods
- In which cases do I need to create two different extension methods for IEnumerable and IQueryable?
- Entity Framework 6 Compiled LINQ Query
- LINQ ToList().Take(10) vs Take(10).ToList() which one generates more efficient query
- LINQ-to-SQL Compiled Query Problem (works as uncompiled query)
- What's the purpose of adding compiled Func methods together?
- Is there any way to create a LINQ query as a variable without having the data source (yet)?
- Paginating a linq query which uses OrderBy
- EF Code First: Methods that can translate to SQL
- Compiled LINQ query & DataLoadOptions... with a twist!
- LINQ Source Code Available
- Which LINQ query to select rows from 1 table that are not in another table
- prevent unnecessary cross joins in count query of generated sql code
- Linq Compiled Query using Contains (Like SQLs IN statement)
- .NET 4 Code Contracts: "requires unproven: source != null"
- EF Code First comparing null values generates strange query
- Linq query syntax and extension methods
- Which is fast : Query Syntax vs. Loops
- linq - how do you do a query for items in one query source that are not in another one?
- How to write LINQ IN clause query which will work as LIKE operator as well?
- IQueryable methods are not resolved for dynamic query variable
More Query from same tag
- How to get a sum of children values on one LINQ
- ParallelQuery.ForAll and IEnumerable.ForEach
- LINQ query does not return child fields
- Getting an type conversion error while using linq in entity framework
- NHibernate LINQ queries with nested .Any() conditions
- Linq to dataset and display linq result in repeater control
- LINQ result form 1:* relationship table -ASP.NET
- best way to use LINQ to query against a list
- evaluate a LambdaExpression?
- Linq expression multiple left outer join error
- Dynamically Run IQueryable Method
- How can I join two tables by a foreign key table in Entity Framework?
- Convert foreach in a single query
- LINQ query Where ID does not exist as a property in a list of objects
- How to do a projection on json string
- How can I return the Value from a .NET IGrouping via a Key?
- asp.net mvc 4.0 linq query with datetime field returns something like this /Date(1391600738810)/
- How to use TimeZoneInfo.ConvertTimeFromUtc in linq to sql?
- Visual Studio assumes return value from FirstOrDefaultAsync() cannot be null
- Filter some unique Data with LINQ and C#
- Where clause Linq not finding column
- How can I structure nHibernate QueryOver where (X AND Y) OR (null AND null)
- Type casting, a runtime alternative to Cast<T>?
- Initializing Lookup<int, string>
- Setting property while enumerating over IOrderedEnumerable<> doesn't set property on object in collection
- What's the best way to acquire a list of strings that match a string inside a string, by looking through a string list?
- MongoDB Query<T>.Where(Expr) converts number Types to string
- Entity Framework - "Unable to create a constant value of type 'Closure type'..." error
- Multiple WHERE. Is there a possibility that a specific WHERE can only be executed in LINQ?
- Can't use Descendants() or Elements() with xmlns