66

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?

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
Anish
  • 3,045
  • 3
  • 27
  • 29
  • @HenkHolterman: It can occasionally be useful; I've written that once or twice. – SLaks Nov 22 '11 at 16:37
  • 4
    You're looking for the documentation. – SLaks Nov 22 '11 at 16:38
  • Is this a duplicate of [Linq: What is the difference between Select and Where](http://stackoverflow.com/questions/1212746) ? – Khan Jan 29 '14 at 21:35
  • Does this answer your question? [Linq: What is the difference between Select and Where](https://stackoverflow.com/questions/1212746/linq-what-is-the-difference-between-select-and-where) – malat Oct 06 '20 at 15:17

2 Answers2

94

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

George Duckett
  • 31,770
  • 9
  • 95
  • 162
  • So where is more like the sql select statement? – Jeremy Mar 23 '16 at 21:05
  • No, WHERE in LINQ and SQL is used to filter the results, and SELECT projects the results in both LINQ and SQL – George Duckett Mar 23 '16 at 21:26
  • 1
    The SELECT statement controls what gets returned for each result data row, did example you could have a firstname and lastname field and have the select change it to fullname = firstname + " " + lastname, so the data you queried had 2 fields but the results of the query had 1. – George Duckett Mar 23 '16 at 23:13
  • 12
    Yeah, I figured it out. I just don't know why people keep using words like "projection" when they could just use more simple and direct phrases like "controls what gets returned" or even "allows the developer to choose which columns are returned". I didn't even know "projection" was a part of the developer lexicon much less what it meant in this context. "pick your columns [or class properties]" does. – Jeremy Mar 24 '16 at 13:07
  • 1
    @Jeremy projection is a term from database theory. But I agree it is not as common as other ways of explaining what SELECT does. – StayOnTarget May 08 '19 at 16:45
30

Where() is a filter.

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

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964