c# - 创建可重用的 Linq 查询

标签 c# entity-framework linq linq-to-entities

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

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

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

var results1 = query.Where(condition1);
...
var results2 = query.Where(condition2);

最佳答案

你走在正确的轨道上。

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

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

然后您可以从该方法可见的任何地方使用它:

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

关于c# - 创建可重用的 Linq 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3522460/

相关文章:

c# - 如何在没有附加类的情况下解析 json?

c# - 在 ASP.NET 5/MVC 6 中使用 IDistributedCache 和 Redis - 类型或命名空间 'Microsoft.Caching' 不存在

c# - EF Core 如何选择具有多对多关系的实体

c# - Entity Framework : adding to one-to-many relationship gives concurrency exception

c# 对自定义列表进行排序

c# - 为什么 C# 中需要 "new"关键字

c# - 提高在 wpf 中绘制平铺位图的性能

MySql Entity Framework 数据库优先 - 主键=长?

c# - 如何在 LINQ 连接中使用 AND

c# - 内部报告所需的复杂小计