我有一個測試幾乎200個案例的謂詞處理程序,每個測試涉及5個可能的比較。我想簡化這些代碼,但是如何在語法上表達這種語法會遇到困難。用於重複比較的謂詞表達式函數
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次,唯一不同的情況是每次都檢查字段名稱。我想盡可能地減少這些代碼。
我希望你沒有使用-1作爲'value'的哨點 - TryParse保證設置值,不管是什麼;如果它返回false,它將把value設置爲0.換句話說,只有當f.TextValue解析爲-1時,value纔會等於-1。你爲什麼不檢查'TryParse'的返回值? – phoog 2012-07-30 22:42:58