Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Enumerable.ToDictionary only retrieve what it needs?

I'm using Enumerable.ToDictionary to create a Dictionary off of a linq call:

return (from term in dataContext.Terms
        where term.Name.StartsWith(text)
        select term).ToDictionary(t => t.TermID, t => t.Name);

Will that call fetch the entirety of each term, or will it only retrieve the TermID and the Name fields from my data provider? In other words, would I be saving myself database traffic if I instead wrote it like this:

return (from term in dataContext.Terms
        where term.Name.StartsWith(text)
        select new { term.TermID, term.Name }).ToDictionary(t => t.TermID, t => t.Name);
like image 754
Mike Pateras Avatar asked Jan 23 '23 18:01

Mike Pateras


1 Answers

Enumerable.ToDictionary works on IEnumerable objects. The first part of your statement "(from ... select term") is an IQueryable object. Queryable is going to look at the expression and build the SQL statement. It will then convert that to an IEnumerable to pass to ToDictionary().

In other words, yes, your second version would be more efficient.

like image 65
James Curran Avatar answered Apr 30 '23 10:04

James Curran