如何追加到EX pressionEX、pression

由网友(一脸美人痣)分享简介:根据从昨天我的问题:如果我不得不追加到我的存在',其中'EX pression,我将如何添加?if I had to append to my existing 'where' expression, how would i append?Expression client...

根据从昨天我的问题:

如果我不得不追加到我的存在',其中'EX pression,我将如何添加?

if I had to append to my existing 'where' expression, how would i append?

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

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

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

,用户可以输入任姓或名或两者。如果他们同时输入我要追加到EX pression。想看看是否有一个相当于追加了在那里我可以做

The user can input either first name or last name or both. If they enter both i want to append to the expression. Trying to see if there is an equivalent of an append where i could do

clientWhere.Append or clientWhere += add new expression

或类似的东西。

or something similar

推荐答案

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

I believe you can just do the following:

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

如果你需要把一切都在防爆pression -land(与的IQueryable 来使用),你也可以做到以下几点:

If you need to keep everything in Expression-land (to use with IQueryable), you could also do the following:

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

这可以通过定义这种扩展方法进行更简洁:

This can be made less verbose by defining this extension method:

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

然后就可以使用语法是这样的:

You can then use syntax like this:

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);
}
阅读全文

相关推荐

最新文章