Difference between IEnumerable vs IQueryable in .NET C#

Yes both will give you the same result but deferred execution.

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.

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. And then filter it as per your requirement.

See.

IEnumerable<Student> students = myModel.GetStudent();
var studentsOver25 = students.Where(p => p.ID >= 25);

What happens here is the database loads all of the students, and passes them across to your program. Your program then filters the data. In essence, the database does a “SELECT * FROM Student”, and returns EVERY Student to you. And then put a filter of ID >= 25. This will load all records of student to memory and then put filter on it.

IQueryable<Student> students = myModel.GetStudent();
var studentsOver25 = students.Where(p => p.ID >= 25);

Code looks quite same but difference in execution database does a “SELECT * FROM Student where ID >= 25” from a performance standpoint it will return only record with ID > 25 .

Advertisements
This entry was posted in C#.NET and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s