0

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());
3

2 Answers 2

5

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.

0

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.

2
  • so can we conclude that need lazy loading => no need to list, no need lazy loading => tolist?
    – myfinite
    Oct 1, 2014 at 4:25
  • No. When the method that contains the db access returns, the db access should be completely executed. When you put an IQueryable<T> into the view, an exception should occur, because the db context has been closed and disposed. Everything else is incredibly bad style IMHO. Imagine having to debug a weird error that originates from your data access layer, but occurs in your view engine.
    – bstenzel
    Oct 1, 2014 at 6:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.