myfinite
myfinite

Reputation: 89

To list and without tolist

I would like to know when to use tolist. In the following example, both of the following do not result in error. So, which way to use?

 var employees = db.Employees.Include(e => e.Department);
            return View(employees);

 var employees = db.Employees.Include(e => e.Department);
            return View(employees.ToList());

Upvotes: 0

Views: 2231

Answers (2)

Vikas Gupta
Vikas Gupta

Reputation: 4465

Seems like the code is ASP.Net MVC code.. given return View(employees); I also assume that the data is being pulled from the DB, using some LinqToSQL or EntityFramework like technology.

Given those two assumptions, I'd recommend that the latter be used. i.e. with .ToList() Reason being, if the query is lazily evaluated, if you pass employees without .ToList(), you are essentially passing the query to the View, and it will execute when query is enumerated while rendering the View. View rendering should be fast, and not be blocked by a call to database. .ToList() would avoid that, and force execution of the query in controller, and View will have data available in memory, for fast rendering...

Hope it answers your question.

EDIT: One caveat.. there some scenarios, for example when building APIs, like with OData APIs with WebAPI, that you actually want to return the query than the materialized list. The reason there is that by design, you want Framework to build on top of that query, before the filtered data is returned to the caller. In other words, framework does some more leg work for you, before view (serialized data - typically not HTML) is actually rendered.

Upvotes: 5

Nicky
Nicky

Reputation: 75

After the first line is executed, employees collection will not be loaded into the memory (Lazy Loading). It is loaded when the collection is first accessed. When you call ToList() collection will be forced to be loaded into memory.

Usage is based on the trade-off between memory limitation and speed. Accessing from the memory is faster than lazy loading.

Upvotes: 0

Related Questions