创建可重用的Linq查询

dst*_*str 3 c# linq linq-to-entities entity-framework

我有一个选择查询,它使用不同的where过滤器反复使用:

var query = from row in context.Table select row;
Run Code Online (Sandbox Code Playgroud)

如何将其保存到静态类变量中,以便可以在不同的方法中重用它?喜欢:

var results1 = query.Where(condition1);
...
var results2 = query.Where(condition2);
Run Code Online (Sandbox Code Playgroud)

p.c*_*ell 5

你走在正确的轨道上.

考虑创建一个新方法而不是变量:

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

然后,您可以从方法可见的任何位置使用它:

 //Active Customers with no invoices due.
 var activePaidCustomers = ListActiveCustomers().Where(c=>c.InvoicesDue==0)
                                                .OrderByDescending(c=>c.LastPaidOn)
                                                .ToList();
Run Code Online (Sandbox Code Playgroud)