.Net C# – LINQ IQueryable

0 Comments

I ran into a problem while working on an application using LINQ.  I had a method that had a return type of IQueryable, and I was unable to loop through the data in the object.  When using LINQ, you have to use IQueryable or IEnumerable (or another similar datatype) as the datatype when you create an Anonymous type using a LINQ query.

This would create an Anonymous type:

public IQueryable GetEmployees()
{
     return from e in this.Employees
     where e.Active == 1
     select new
     {
          ID = e.ID,
          Name = e.FirstName + " " + e.LastName
     };
}

Basically, I only wanted to return the employee’s ID and the employee Name. I didn’t need any other information from the Employee table. However, since I used the “select new”, LINQ creates it as an Anonymous type.

Now the problem I was running into is that when I returned the data from a separate class, I could not loop through the data using a “foreach” loop.

So after hours of research and numerous posts on a number of programming forums, I finally found why I couldn’t loop through the data in an IQueryable object. IT’S NOT POSSIBLE!!

Basically, if you are returning data that you are going to databind to a control(DataGridView, ComboBox, etc.), and you will NEVER want to do anything with the data after it’s returned, then using IQueryable will work just fine.

However, if there is a chance that you may want to do something else with the data, then return it as some other datatype. Personally, I have started converting the return datatype to a generic list object. Similar to this:

public List<Employee> GetEmployees()
{
     return (from e in this.Employees
                where e.Active == 1
                select e).ToList();
}

Hopefully, this will help out anyone who is in the same situation I was in.

Tags: , ,

Leave a Reply