I have some code which I would like to refactor, but I don't know how to do it. The code in question repeats itself, except for an expression which varies.
The code:
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
and not
are Boolean values.
This code is repeated several times, except that c1.Address.PostalCode
could be c1.Address.City
, or even c1.User.PhoneNumber
.
Can I somehow refactor this so that I can use a method and inject the c1.Address.PostalCode
? Something like this:
if (equal && not)
first = c1 => <variable> != newTerm;
...
else if (not)
first = c1 => !<variable>.Contains(newTerm);
It looks like this post is what I'm looking for:
Property Name to Lambda Expression C#
But I need to go a little further, because the Address property is a class itself, which of course has properties, one of which is PostalCode.