用参数替换Where子句Lambda中的运算符 [英] replacing operator in Where clause Lambda with a parameter

查看:69
本文介绍了用参数替换Where子句Lambda中的运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用传递给方法的参数替换linq lambda子句中的运算符(==,> =,> ...)

i want to replace operator(==, >= ,>...) in the clause where of linq lambda with parameter passed in method

方法:

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替换子句中的== 获得这样的东西

i want to replace == in the clause where with the parameter filter to obtain something like this

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

任何人都知道如何使它起作用吗?

any body knows how to make it work ?

推荐答案

我认为最好用字符串过滤器和相应的委托人来制作字典.

I think it's better to make dictionary out of string filters and corresponding delegates.

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));

        ...
     }
}

这篇关于用参数替换Where子句Lambda中的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆