LINQ Tips: Querying disposable objects in an using block

Be careful while querying the disposable object inside an using block, you may find that the yielded objects are all disposed before you have used them. To get over this issue use the ToList() method. You can exit the using block, and yield the results out.

Example:

IEnumerable<Student> results;
using (var db = new StudentDataContext())
{
  results = db.Students.Where(...).ToList();
}
foreach (var student in results)
{
  SomeMethod(student);
  yield return student;
}

Published 02-10-2009 8:43 PM by shahed

Comments

# re: LINQ Tips: Querying disposable objects in an using block

Thursday, February 12, 2009 11:38 PM by montasir

thnx

Powered by Community Server (Non-Commercial Edition), by Telligent Systems