views:

51

answers:

5

I have a select query which is used over and over with different where filters:

var query = from row in context.Table select row;

How can I save this into a static class variable so I can reuse it in different methods? Like:

var results1 = query.Where(condition1);
...
var results2 = query.Where(condition2);
+1  A: 

Simply replace var with IEnumerable<RowType> (or IQueryable<RowType>) where RowType is the (non-anonymous) type of each item in the result sequence:

static IEnumerable<RowType> query = from ... select row; // row is of RowType.
Mehrdad Afshari
+2  A: 

This code:

var query = from row in context.Table select row;

Is functionally equivalent to:

var query = context.Table;

So you don't need to keep this query variable to reuse it, just use context.Table directly:

var results1 = context.Table.Where(condition1);
...
var results2 = context.Table.Where(condition2);
Thomas Levesque
+1  A: 

Well, the first step is finding out the exact type of query. The easiest way is to step through so code using it in the debugger, and see what it says the type is (probably IQueryable<RowType> or IOrderedQueryable<RowType>)

James Curran
+1  A: 

Something like this:

Expression<Func<TypeYoureQueryingAgainst, bool>> query = p => p.Value == someValue; // etc..

Then you could do the following, where TypeYoureQueryingAgainst is in the repository or whatever pattern you're using:

repository.Where(query);

Hope that makes sense..

Ian P
Makes sense...somewhat. How do I send parameter to it? I've created this: Expression<Func<MyTable, int, bool>> query = (table, id) => table.Id == id;. I can use it as context.MyTable.Where(query) but how can I send id parameter to "query"?
Armagan
+2  A: 

You're on the right track.

Consider creating a new method instead of a variable:

public IQueryable<Cust> ListActiveCustomers()
{
     return dataContext.Customers.Where(c=>c.IsActive==true);
}

You can then consume this from anywhere that method is visible:

 //Active Customers with no invoices due.
 var activePaidCustomers = ListActiveCustomers().Where(c=>c.InvoicesDue==0)
                                                .OrderByDescending(c=>c.LastPaidOn)
                                                .ToList();
p.campbell
Since I don't have a global ObjectContext I've created a parameterized List() method: private IQueryable<Cust> List(MyContext ctx){ return ctx.Customers...}..
Armagan