我有一些我想重构的代码,但我不知道该怎么做。有问题的代码会重复,除了表达式有所不同。
代码:
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));
}
equal
和not
是布尔值。
此代码重复多次,但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。