为以下where条件创建谓词
本文关键字:创建 谓词 条件 where | 更新日期: 2023-09-27 18:27:22
我看了很多帖子,但找不到问题的答案。
我有很多使用Where条件的查询,如下所示。在代码中,它看起来很难看,所以我想使用谓词(不知道它是否可能)。
.Where(i => i.Timestamp <= date.ToUniversalTime() && i.Timestamp >= yearStart.ToUniversalTime())
我想把它变成
.WhereYearTotal(date)
因此可以在"WhereYearTotal"函数中评估条件。
编辑:
我已经尝试过扩展方法,但它似乎在嵌套查询中不起作用,例如:
var query = (from o in db.tableA
select new {
monthly = db.tableA.WhereYearTotal(date),
}).FirstOrDefault();
我得到一个Null引用异常。
看看LINQKit。我会让你做你想做的事。
这是使用扩展方法完成的。你需要为它创建一个静态类和一个静态方法
static class MyHelper
{
public static IEnumerable<T> WhereYearTotal(this IEnumerable<T> input, DateTime d)
{
return input.Where( ... )
}
}
// usage : (the namespace for MyHelper must be in your using list)
myCollection.WhereYearTotal( DateTime.Now );
只需为IQueryable编写自己的扩展方法:
public static IQueryable<TSource> WhereYearTotal<TSource>(
this IQueryable<TSource> source,
DateTime date ) {
return source.Where(i => i.Timestamp <= date.ToUniversalTime() && i.Timestamp >= yearStart.ToUniversalTime());
}
Predicate
是作为参数传递给Where
的方法。您想要的不是谓词,而是扩展方法
namespace ExtensionMethods
{
public static class MyExtensions
{
public static IEnumerable<MyClass> WhereYearTotal(this IEnuerable<MyClass> source, DateTime date)
{
return source.Where(i => i.Timestamp <= date.ToUniversalTime() && i.Timestamp >= yearStart.ToUniversalTime())
}
}
}