Skip to main content
 首页 » 编程设计

c#之用参数替换 Where 子句 Lambda 中的运算符

2024年02月23日14qlqwjy

我想用方法中传递的参数替换 linq lambda 的 where 子句中的 operator(==, >= ,>...)

方法:

public IEnumerable<Localisation> GetByFiltre(string filter, string valeurDate1) 
 
/* 
filter has the value of an operator: 
> 
== 
!= 
>= 
<= 
*/ 
 
    DateTime dt = Convert.ToDateTime(valeurDate1); 
 
    var mod = from o in new GpsContext().Locals.Where(loc => loc.Date == dt) 

我想用参数 filter 替换 where 子句中的 == 获得这样的东西

     var mod = from o in new GpsContext().Locals.Where(loc => loc.Date filter dt) 

有人知道如何让它发挥作用吗?

请您参考如下方法:

我认为最好用字符串过滤器和相应的委托(delegate)来制作字典。

class YourClass 
{ 
     static readonly Dictionary<string, Func<DateTime, DateTime, bool>> s_filters = new Dictionary<string, Func<DateTime, DateTime, bool>> 
     { 
       {  ">", new Func<DateTime, DateTime, bool>((d1, d2) => d1  > d2) } 
       { "==", new Func<DateTime, DateTime, bool>((d1, d2) => d1 == d2) } 
       { "!=", new Func<DateTime, DateTime, bool>((d1, d2) => d1 != d2) } 
       { ">=", new Func<DateTime, DateTime, bool>((d1, d2) => d1 >= d2) } 
       { "<=", new Func<DateTime, DateTime, bool>((d1, d2) => d1 <= d2) } 
     }; 
 
     public IEnumerable<Localisation> GetByFiltre(string filter, string valeurDate1) 
     { 
        ... 
 
        DateTime dt = Convert.ToDateTime(valeurDate1); 
        var filterDelegate = s_filters[filter]; 
 
        var mod = from o in new GpsContext().Locals.Where(loc => filterDelegate(loc.Date,dt)); 
 
        ... 
     } 
}