gpt4 book ai didi

c# - 如何附加到表达式

转载 作者:IT王子 更新时间:2023-10-29 03:59:49 24 4
gpt4 key购买 nike

基于 my question from yesterday :

如果我必须附加到我现有的“where”表达式,我将如何附加?

Expression<Func<Client, bool>> clientWhere = c => true;

if (filterByClientFName)
{
clientWhere = c => c.ClientFName == searchForClientFName;
}

if (filterByClientLName)
{
clientWhere = c => c.ClientLName == searchForClientLName;
}

用户可以输入名字或姓氏,或同时输入两者。如果他们都输入我想附加到表达式。尝试查看是否有等效于我可以做的追加

clientWhere.Append or clientWhere += add new expression

或类似的东西

最佳答案

我相信你可以做到以下几点:

Expression<Func<Client, bool>> clientWhere = c => true;

if (filterByClientFName)
{
var prefix = clientWhere.Compile();
clientWhere = c => prefix(c) && c.ClientFName == searchForClientFName;
}
if (filterByClientLName)
{
var prefix = clientWhere.Compile();
clientWhere = c => prefix(c) && c.ClientLName == searchForClientLName;
}

如果您需要将所有内容保存在 Expression 中(与 IQueryable 一起使用),您还可以执行以下操作:

Expression<Func<Client, bool>> clientWhere = c => true;

if (filterByClientFName)
{
Expression<Func<Client, bool>> newPred =
c => c.ClientFName == searchForClientFName;
clientWhere = Expression.Lambda<Func<Freight, bool>>(
Expression.AndAlso(clientWhere, newPred), clientWhere.Parameters);
}
if (filterByClientLName)
{
Expression<Func<Client, bool>> newPred =
c => c.ClientLName == searchForClientLName;
clientWhere = Expression.Lambda<Func<Freight, bool>>(
Expression.AndAlso(clientWhere, newPred), clientWhere.Parameters);
}

这可以通过定义这个扩展方法变得不那么冗长:

public static Expression<TDelegate> AndAlso<TDelegate>(this Expression<TDelegate> left, Expression<TDelegate> right)
{
return Expression.Lambda<TDelegate>(Expression.AndAlso(left, right), left.Parameters);
}

然后您可以使用如下语法:

Expression<Func<Client, bool>> clientWhere = c => true;
if (filterByClientFName)
{
clientWhere = clientWhere.AndAlso(c => c.ClientFName == searchForClientFName);
}
if (filterByClientLName)
{
clientWhere = clientWhere.AndAlso(c => c.ClientLName == searchForClientLName);
}

关于c# - 如何附加到表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1266742/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com