c# - How to I chain methods from a list so that the result from one becomes the input of the next? -


i have list of processor objects contain execute method. want execute each processor.execute() in order list, want result 1 become input next , on until last 1 in list becomes final result.

my code this

    private idocument execute(idocument document, list<iprocessor> processors)     {         idocument result = document;         foreach (iprocessor p in processors)         {             result = p.execute(document);         }          //return result;     } 

i don't know ahead of time how many processors there in list, same (i.e. method signatures execute methods same)

i assume want feed in updated result variable input:

private idocument execute(idocument document, list<iprocessor> processors) {     idocument result = document;     foreach (iprocessor p in processors)     {         result = p.execute(result);     }                      // ^ here      return result; } 

you can express method more concisely using linq:

private idocument execute(idocument document, list<iprocessor> processors) {     return processors.aggregate(document, (res, proc) => proc.execute(res)); } 

Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -