3 ms·
Right, this is a bit different and not really seamless (e.g. an object database wouldn't require a ToList()). The ability to express queries this way is nice, t
by atombender 8y ago
Right, this is a bit different and not really seamless (e.g. an object database wouldn't require a ToList()). The ability to express queries this way is nice, though.
- scarface74 8y agoThe idea of ToList(), .Count() etc., is that the query isn’t executed until you use such a function, you can keep composing the query and it will be translated and run on the server instead of the client. For instance.... var seniors = customers.Where(c => c.Age > 65).ToList() foreach(c in seniors) {} Will be translated to a query and run on the database server. var seniors = customers.ToList().Where(c => c.age > 65) foreach(c in customers) {} Will give you back the same results, but you will get back every record in the table/collection and the filtering will be done client side. Btw: The first query could be rewritten as var seniors = (from c in Customers where c.Age > 65).ToList(). You would only do .ToList() if you want to keep the scope of the connection small if for instance you are passing it outside of the class. You can iterate the results directly from the query instead of returning the results in memory (using ToList()) and it would work just like any other database style cursor. EDIT: Just to clarify from my first post, the example should have been List<Customers> Find(Expression<Func<bool,Customer>> predicate) { .... return customers.Where(predicate).ToList(); } This pattern also works great for unit testing. You can mock out your database Context and use a List<T> Customer to store data and you can still test your queries without having a dependency on a database.