Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# extension methods types

In C#, There are two sets of extension methods (such as Where) which works on top of IEnumerable and IQueryable. which of them used for manipulate in-memory objects and which is used for working with database.? Please help

like image 889
Dheeraj Bansal87 Avatar asked Mar 03 '23 00:03

Dheeraj Bansal87


2 Answers

IEnumerable<T>.Where method extension.which accepts a Func<TSource, bool> predicate parameter, forcing the filtering to happen in memory. While querying data from the database,IEnumerable executes select query on the server-side, loads data in-memory on the client-side and then filters the data. For the IEnumerable<T> case, it will be LINQ-to-object, meaning that all objects matching the original query will have to be loaded into memory from the database. IEnumerable is suitable for querying data from in-memory collections like List, Array and so on.

IQueryable<T>.Where method extension, which accepts a Expression<Func<TSource, bool>> predicate parameter. Notice that this is an expression, not a delegate, which allows it to translate the where condition to a database condition.
While querying data from a database, IQueryable executes a select query on server-side with all filters. The difference is that IQueryable<T> is the interface that allows LINQ-to-SQL (LINQ.-to-anything really) to work. So if you further refine your query on an IQueryable<T>, that query will be executed in the database, if possible. IQueryable is suitable for querying data from out-memory (like remote database, service) collections.

like image 172
Reza Jenabi Avatar answered Mar 05 '23 17:03

Reza Jenabi


IEnumerable<T> exposes the enumerator, which supports a simple iteration over a collection of a specified type. so it's for in-memory objects

IQueryable<T> provides functionality to evaluate queries against a specific data source wherein the type of data is known. so it's for working with database

like image 41
Mahdi Asgari Avatar answered Mar 05 '23 16:03

Mahdi Asgari