0

Which query is optimized :

db.news.Select(c => new { c.Title, c.Date, c.ID })
       .SingleOrDefault(c => c.ID == 1);

or

db.news.Where(c => c.ID == 1)
       .Select(c => new { c.Title, c.Date })
       .SingleOrDefault();

I want this query:

select title, date  
where id = 1

in global which one is better where before select, or where after select?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
foad abdollahi
  • 1,733
  • 14
  • 32

1 Answers1

1

Generally, Where before Select (Where first approach) is more performant, since it filters your result set first, and then executes Select for filtered values only.

Kamal24h
  • 70
  • 2
  • 9
  • EF builds a query based on all expressions prior to either a materializing operation (i.e. `ToList`, `AsEnumerable`, etc.) or encountering something that requires client-side evaluation and that feature is enabled. – Steve Py Sep 21 '21 at 10:19
  • 1
    Yet, I think Where first approach is performant. EF builds where first rapidly. However the performance difference between them, could be ignored for most of the applications. – Kamal24h Sep 21 '21 at 10:26