0

I have the following simple switch statement. As you can see, the expressions for Any are almost identical.

My question is:

  1. Is there any way to re-use the expression so that I don't have to repeat it every time I need the same or similar expression.
  2. if not possible to re-use the whole expression in Any, is it possible to re-use "x => x.Question == _question.Question" at least?

Thanks!

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;
                }
4

1 回答 1

1

Assuming in memory Linq 2 Objects, you can use a Func to extract the correct field and reuse the rest of the query; (calling the type of ReportDataItems Itemhere)

        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));
于 2013-05-01T18:40:55.187 回答