Skip to main content
 首页 » 编程设计

c#之自定义 Where 表达式

2024年02月13日16lvdongjie

我有简单的界面:

public interface IValid 
{ 
   DateTime From {get;set;} 
   DateTime? To {get;set;} 
} 

我希望有可能写出这样的简单表达式:

dbContext.SomeClass 
   .WhereValidOnDate(DateTime.Today) 
   .Where(x=> ...more_expressions...) 
   .ToList(); 

我认为,我需要编写一些带有方法签名的类:

public static IQueryable<TSource> WhereValidOnDate<TSource>(this 
    IQueryable<TSource> source) 

在该方法中,我需要进行一些简单的数据比较(硬编码),例如:

x => x.From<= DateTime.Today && (x.To == null || x.To <= DateTime.Today 

我尝试了表达式树 - 有效,但语法有点困惑:

dbContext.SomeClass 
   .Where(IsValidExpression) 
   .Cast<SomeClass>() 
   .Where(x=> ...more_expressions...) 
   .ToList(); 

请您参考如下方法:

试试这个签名和实现:

public static IQueryable<T> WhereValidOnDate<T>(this IQueryable<T> source, DateTime other) 
   where T : IValid 
{ 
    return source.Where(x => x.From<= other && (x.To == null || x.To <= DateTime.Today)); 
}