DEV Community

Discussion on: Dear LINQ, I love you, but I'm going back to my roots

Collapse
 
rafalpienkowski profile image
Rafal Pienkowski • Edited

You should always be careful when you're using LINQ.

There is huge difference between using LINQ on collection which are implementing IEnumerable<T> and IQueryable<T>. Long story short. When we're using IEnumerable interface, as you've written, we're working on objects which are stored in memory. In other hand IQueryable uses expression trees which can be modified as long as we don't execute them (calling ToList() or ToArray() method). More about expression trees.

Common mistake is work on IEnumerable interface. Let's take an example. We've a repository which contains method GetAll() which returns IEnumerable. When we'll work with those implementation like in example below, we'll first load whole collection into memory, then we'll filter results, after that we'll skip 10 elements and at the end we'll take only 5 results.

var elements = _repository.GetAll().Where(a => a.Salary < 100).Skip(10).Take(5);

But if our repository would implement method GetAll() which would return IQueryable expression won't be executed until we explicity call ToList() method. For instance, when we'll work with Entity Framework on a database our expression will be translated into proper SQL query and we'll return only 5 elements (or less if condition won't be full fit) to our program.

To sum up. Be aware during work with LINQ. Check if you're working on IEnumerable or IQueryable interfaces. It matters. Cheers.

BTW difference between IEnumerable and IQueryable is one of my favorite interview questions :)

Collapse
 
s3artis profile image
Matt Weingaertner • Edited

This comment sums the thoughts behind using LINQ up. 👍 Thank you!