C# 为以下where条件创建谓词
我看过很多帖子,但都找不到答案 我有很多使用Where条件的查询,如下所示。在代码中,它看起来很难看,所以我考虑使用谓词(不知道是否可能) 因此,可以在“Where YearTotal”函数中对条件进行评估C# 为以下where条件创建谓词,c#,.net,linq-to-sql,predicate,C#,.net,Linq To Sql,Predicate,我看过很多帖子,但都找不到答案 我有很多使用Where条件的查询,如下所示。在代码中,它看起来很难看,所以我考虑使用谓词(不知道是否可能) 因此,可以在“Where YearTotal”函数中对条件进行评估 编辑: 我已经尝试过扩展方法,但它似乎在嵌套查询中不起作用,例如: var query = (from o in db.tableA select new { monthly = db.tableA.WhereYearTotal(date), }).
编辑: 我已经尝试过扩展方法,但它似乎在嵌套查询中不起作用,例如:
var query = (from o in db.tableA
select new {
monthly = db.tableA.WhereYearTotal(date),
}).FirstOrDefault();
我得到一个空引用异常。这是通过使用创建静态类和静态方法来完成的
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 );
静态类MyHelper
{
公共静态IEnumerable WhereYearTotal(此IEnumerable输入,日期时间d)
{
返回输入。其中(…)
}
}
//用法:(MyHelper的命名空间必须在使用列表中)
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());
}
公共静态IQueryable WhereYearTotal(
这是可靠的消息来源,
日期时间(日期){
返回source.Where(i=>i.Timestamp=yearStart.ToUniversalTime());
}
谓词
是作为参数传递给的方法,其中
。你想要的不是谓词,而是
命名空间扩展方法
{
公共静态类MyExtensions
{
公共静态IEnumerable WhereYearTotal(此IEnumerable源,日期时间日期)
{
返回source.Where(i=>i.Timestamp=yearStart.ToUniversalTime())
}
}
}
看一看。我会让你做你想做的。事实上,在我发布问题后,我也尝试了同样的方法,但有一个问题。我无法在查询中使用扩展方法,如下面所示:code
var query=(从db.tableA中的o选择new{monthly=db.tableA.WhereYearTotal(date),});
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 );
public static IQueryable<TSource> WhereYearTotal<TSource>(
this IQueryable<TSource> source,
DateTime date ) {
return source.Where(i => i.Timestamp <= date.ToUniversalTime() && i.Timestamp >= yearStart.ToUniversalTime());
}
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())
}
}
}