lambda表达式的属性名称

时间:2018-01-11 16:20:15

标签: c# lambda dependency-injection

我有一些我想重构的代码,但我不知道该怎么做。有问题的代码会重复,除了表达式有所不同。

代码:

Expression<Func<SearchModel, bool>> first = null;
if (first == null)
{
    if (equal && not)
        first = c1 => c1.Address.PostalCode != newTerm;
    else if (equal)
        first = c1 => c1.Address.PostalCode == newTerm;
    else if (not)
        first = c1 => !c1.Address.PostalCode.Contains(newTerm);
    else
        first = c1 => c1.Address.PostalCode.Contains(newTerm);
}
else
{
    if (equal && not)
        first = first.Or(c1 => c1.Address.PostalCode != newTerm);
    else if (equal)
        first = first.Or(c1 => c1.Address.PostalCode == newTerm);
    else if (not)
        first = first.Or(c1 => !c1.Address.PostalCode.Contains(newTerm));
    else
        first = first.Or(c1 => c1.Address.PostalCode.Contains(newTerm));
}

equalnot是布尔值。

此代码重复多次,但c1.Address.PostalCode可以是c1.Address.City,甚至是c1.User.PhoneNumber

我可以以某种方式重构这个,以便我可以使用方法并注入c1.Address.PostalCode吗?像这样:

if (equal && not)
    first = c1 => <variable> != newTerm;
...
else if (not)
    first = c1 => !<variable>.Contains(newTerm);

看起来这篇文章正是我要找的:

Property Name to Lambda Expression C#

但我需要更进一步,因为Address属性本身就是一个类,当然它有一个属性,其中一个是PostalCode。

0 个答案:

没有答案