C# – LINQ IQueryable
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: C#, IQueryable, LINQ

Leave a Comment