As Craig Stuntz hinted, the question here is where Customers
comes from and what type it is. If it's an in-memory object, the filtering is all going to happen in memory; if it's an object query, it'll happen on your database server, which is what you want. We can't see enough of your code to know much about Customers
, but I'll suggest a right and wrong example:
Right (more or less):
using (var context = new MyContextType())
{
var Customers = context.Customers;
var query = from d in Customers
select d;
if (!flag)
{
query = from d in query
where d.Orders.Count > 10
select d;
}
return query.ToList();
}
Wrong:
using (var context = new MyContextType())
{
var Customers = context.Customers.ToList(); // ToList triggers the query
var query = from d in Customers
select d;
if (!flag)
{
query = from d in query
where d.Orders.Count > 10
select d;
}
return query.ToList();
}
See the difference? It's the context.Customers.ToList()
. That runs the full query and loads everything into memory before you have a chance to filter it. Make sure you have the query fully built, including where
logic, before you run ToList()
on it.
@Craig - Hope you don't mind me picking up your idea and running with it. I'd have voted for your answer if you had one up.