用参数替换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));
...
}
}