我有一个谓词处理程序,可以测试近 200 个案例,每个测试都涉及五种可能的比较。我想简化这段代码,但在如何用语法表达这一点时遇到了困难。
public static Expression<Func<OADataConsolidated, bool>> Match(DOTSearchFilter filters)
{
var predicate = (filters.OrFilters.Count > 0) ? PredicateBuilder.False<OADataConsolidated>() : PredicateBuilder.True<OADataConsolidated>();
foreach (DOTFilter f in filters.AndFilters)
{
int value = -1;
int.TryParse(f.TextValue, out value);
switch (f.Type)
{
case DOTFilter.FilterType.SCO:
switch (f.IdValue)
{
case 4: // GED: Reasoning
switch (f.Comp)
{
case DOTFilter.Comparitor.LessThan:
predicate = predicate.And(p => p.ajblGEDR_Mean < value);
break;
case DOTFilter.Comparitor.EqualOrLess:
predicate = predicate.And(p => p.ajblGEDR_Mean <= value);
break;
case DOTFilter.Comparitor.EqualTo:
predicate = predicate.And(p => p.ajblGEDR_Mean == value);
break;
case DOTFilter.Comparitor.EqualOrGreater:
predicate = predicate.And(p => p.ajblGEDR_Mean >= value);
break;
case DOTFilter.Comparitor.GreaterThan:
predicate = predicate.And(p => p.ajblGEDR_Mean > value);
break;
}
break;
case 5: // GED: Mathematics
switch (f.Comp)
{
case DOTFilter.Comparitor.LessThan:
predicate = predicate.And(p => p.ajblGEDM < value);
break;
case DOTFilter.Comparitor.EqualOrLess:
predicate = predicate.And(p => p.ajblGEDM <= value);
break;
case DOTFilter.Comparitor.EqualTo:
predicate = predicate.And(p => p.ajblGEDM == value);
break;
case DOTFilter.Comparitor.EqualOrGreater:
predicate = predicate.And(p => p.ajblGEDM >= value);
break;
case DOTFilter.Comparitor.GreaterThan:
predicate = predicate.And(p => p.ajblGEDM > value);
break;
}
break;
上面的 switch 语句被重复了近 200 次,唯一不同的是每次检查的字段名称。我想尽可能减少这段代码。