Difference between Select and Where in Entity Framework

C#.NetLinqEntity FrameworkLinq to-Sql

C# Problem Overview


What is the difference between .Select() and .Where() in Entity Framework? Eg

return ContextSet().Select(x=> x.FirstName == "John")

vs

ContextSet().Where(x=> x.FirstName == "John")

When should I use .Select vs .Where?

C# Solutions


Solution 1 - C#

Select is a projection, so what you get is the expression x=> x.FirstName == "John" evaluated for each element in ContextSet() on the server. i.e. lots of true/false values (the same number as your original list). If you look the select will return something like IEnumerable<bool> (because the type of x=> x.FirstName == "John" is a bool).

Where filters the results, returning an enumerable of the original type (no projection).


So, use Select when you want to keep all results, but change their type (project them).

Use Where when you want to filter your results, keeping the original type

Solution 2 - C#

Where() is a filter.

Select() selects a different piece of data.
Your Select() example will return a collection of booleans.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnishView Question on Stackoverflow
Solution 1 - C#George DuckettView Answer on Stackoverflow
Solution 2 - C#SLaksView Answer on Stackoverflow