How to simply a foreach iteration using reflection

Posted by Priya on Stack Overflow See other posts from Stack Overflow or by Priya
Published on 2010-03-31T10:17:35Z Indexed on 2010/03/31 10:23 UTC
Read the original article Hit count: 419

Filed under:
|

Consider that I have to get the overall performance of X. X has Y elements and Y in turn has Z elements which inturn has some N elements. To get the performance of X I do this:

List<double> XQ = new List<double>();
foreach (Elem Y in X.Y){
   List<double> YQ = new List<double>();
   foreach (Elem Z in Y.Z){
      List<double> ZQ = new List<double>();
      foreach (Elem N in Z.N){
         ZQ.Add(GetPerformance(N));
      }
      YQ.Add(AVG(ZQ));
   }
   XQ.Add(AVG(YQ));
}

AVG of XQ list gives the performance of X. The performance can be calculated for either X or Y or for Z. X, Y and Z share the same base class. So depending on the item given the foreach loop has to be executed. Currently I have a switch case to determine each item (X or Y or Z) and the foreach loop is repeated in the code pertaining to the item (eg. If Y foreach starts from Y.Z). Is is possible to convert this whole code generic using reflection instead of having to repeat it in each switch case?

Thanks

© Stack Overflow or respective owner

Related posts about reflection

Related posts about generic