创建可重用的Linq查询 [英] Creating reusable Linq queries

查看:53
本文介绍了创建可重用的Linq查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个选择查询,该查询一遍又一遍地与不同的where过滤器一起使用:

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);

推荐答案

您在正确的轨道上.

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

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();

这篇关于创建可重用的Linq查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆