1) There are many differences but let us discuss about the one big difference which makes the biggest difference. “IQueryable” interface is useful when your collection is loaded using LINQ or Entity framework and you want to apply filter on the collection.
Consider the below simple code which uses “IEnumerable” with entity framework. It’s using a “where” filter to get records whose “EmpId” is “2”.
2) The main difference is that with IEnumerable you get all the records at once while with IQueryable you only get the records that you want, let’s see that in action with an example:
Let’s assume that you have a client table with all your client’s information (approximately 1000 clients)
If you use IEnumerable to get the first 5 customers you end up loading all 1000 and then selecting the first 5.
With IQueryable you only select the first 5 (saving a lot of resources !)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
static void Main(string[] args)
{
using (var db = new MyDbContext())
{
IEnumerable<Client> clients = db.Clients.Take(5).ToList();
// ToList() executes the query straight away
// All the list of clients is loaded into memory (1000 clients)
// After that, only the first 5 are selected
IQueryable<Client> sameClients = db.Clients.Take(5).ToList();
// ToList() executes the query straight away
// The first 5 clients are loaded into memory
}
}
|
No comments:
Post a Comment