是否可以创建一个自定义lambda函数,以替换为下面的.Contains()/.StartsWith()/ EndsWith()调用?
如果是这样,我不必在这里比较搜索字符串,但是可以在此自定义函数中进行比较.如果我是对的,这将删除下面代码的2/3.
…或者如果您对如何将其最小化有其他想法,我将很高兴听到!
private void searcher(ref Expression<Func<Party, bool>> predicate, string search, string keyword, string column)
{
if (search == "contain")
{
if (column == "surname") predicate = predicate.And(p => p.surname.Contains(keyword));
if (column == "lastname") predicate = predicate.And(p => p.lastname.Contains(keyword));
if (column == "comment") predicate = predicate.And(p => p.comment.Contains(keyword));
if (column == "position") predicate = predicate.And(p => p.position.Contains(keyword));
}
else if (search == "start")
{
if (column == "surname") predicate = predicate.And(p => p.surname.StartsWith(keyword));
if (column == "lastname") predicate = predicate.And(p => p.lastname.StartsWith(keyword));
if (column == "comment") predicate = predicate.And(p => p.comment.StartsWith(keyword));
if (column == "position") predicate = predicate.And(p => p.position.StartsWith(keyword));
}
else if (search == "end")
{
if (column == "surname") predicate = predicate.And(p => p.surname.EndsWith(keyword));
if (column == "lastname") predicate = predicate.And(p => p.lastname.EndsWith(keyword));
if (column == "comment") predicate = predicate.And(p => p.comment.EndsWith(keyword));
if (column == "position") predicate = predicate.And(p => p.position.EndsWith(keyword));
}
}
解决方法:
可能会尝试为字符串编写扩展名(请注意,使用where枚举可能会更好):
public static bool Exists(this string str, string where, string what)
{
if(where == "start") return str.StartsWith(what);
if(where == "end") return str.EndsWith(what);
if(where == "contain") return str.Contains(what);
return false;
}
然后,您的代码将变得更简单:
private void searcher(ref Expression<Func<Party, bool>> predicate, string search, string keyword, string column)
{
if (column == "surname") predicate = predicate.And(p => p.surname.Exists(search ,keyword));
if (column == "lastname") predicate = predicate.And(p => p.lastname.Exists(search ,keyword));
if (column == "comment") predicate = predicate.And(p => p.comment.Exists(search ,keyword));
if (column == "position") predicate = predicate.And(p => p.position.Exists(search ,keyword));
}