我有以下简单的switch语句。如您所见,Any的表达式几乎相同。
我的问题是:
谢谢!
switch (_question.DataField)
{
case DataField.FormData:
result = Report.ReportDataItems.Any(
x => x.Question == _question.Question
&& (!string.IsNullOrEmpty(x.FormData)) && Int32.TryParse(x.FormData, out tempVal));
break;
case DataField.FormData2:
result = Report.ReportDataItems.Any(
x => x.Question == _question.Question
&& (!string.IsNullOrEmpty(x.FormData2)) && Int32.TryParse(x.FormData2, out tempVal));
break;
}
答案 0 :(得分:1)
假设在内存Linq 2对象中,您可以使用Func
提取正确的字段并重用查询的其余部分; (在此处调用ReportDataItems Item
的类型)
Func<Item, string> fn;
switch (_question.DataField)
{
case DataField.FormData:
fn = x => x.FormData;
break;
case DataField.FormData2:
fn = x => x.FormData2;
break;
default:
throw new NotImplementedException();
}
result = Report.ReportDataItems.Any(
x => x.Question == _question.Question
&& (!string.IsNullOrEmpty(fn(x)))
&& Int32.TryParse(fn(x), out tempVal));