Recommendation 29: Distinguish between Ienumerable<t> and IQueryable in LINQ queries<T>
LINQ queries provide a total of two types of extension methods, under the System.Linq namespace, there are two static classes: The Enumerable class, which extends for collections that inherit the Ienumerable<t> interface; Queryable class, It expands on the collection class that inherits the Iqueryable<t> interface. Interface Iqueryable<t> also inherits the Ienumerable<t> interface, so the method that causes two interfaces is to a large extent consistent.
LINQ queries can actually be functionally divided into 3 classes: LINQ to OBJECTS, LINQ to SQL, LINQ to XML. The purpose of designing two sets of interfaces is to differentiate between LINQ to OBJECTS and LINQ to SQL, both of which are used internally for query processing in completely different mechanisms. For LINQ to objects, use the extension methods in enumerable to sort and query local collections, and query parameters accept func<>. Func<> is called a predicate expression, which is equivalent to a delegate. For LINQ to SQL, the extension method in queryable is used, which accepts expression<>. Expression<> for packaging func<>. LINQ to SQL eventually translates the expression tree into the appropriate SQL statement and then executes it in the database.
Simply put: Local data source with IENUMERABLE<T>, remote data source with iqueryable<t>.
While using ienumerable<t> and iqueryable<t>, it is also important to note that the logic of,ienumerable<t> queries can be directly used in our custom approach, and iqueryable<t > cannot use a custom method, it must first generate an expression tree, and the query is processed by the LINQ to SQL engine. When using a iqueryable<t> query, if you use a custom method, an exception is thrown.
DataContext CTX =NewDataContext ("server=192.168.0.102;database=temp;uid=sa;pwd=sa123"); Table<Person> persons = CTX. Gettable<person>(); varTemp1 = fromPinchPersonswhereOlderThan20 (P.age)Selectp; foreach(varIteminchTemp1) {Console.WriteLine (string. Format ("Name:{0}\tage:{1}", item. Name, item. Age)); }
Throw exception NotSupportedException: Method "Boolean OlderThan20 (Int32)" does not support conversion to SQL.
However, if we convert the query into a ienumerable<t> query, this pattern is supported:
list<intnew list<int A , }; var from inch where Select C;
Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia
Go to write high-quality Code 157 recommendations for improving C # Programs--recommendation 29: Distinguish between Ienumerable<t> and Iqueryable<t> in LINQ queries;