I am trying to invoke a function for every member of a list, but pass additional parameters to the delegate.
if I have a list called documents
List<string> documents = GetAllDocuments();
Now I need to iterate over the documents and call a method for every entry. I can do it using something like
documents.ForEach(CallAnotherFunction);
This would require the CallAnotherFunction to have a definition like
public void CallAnotherFunction(string value)
{
//do something
}
However, I need another parameter in CallAnotherFunction called, say content, that is dependent on the calling list.
So, my ideal definition would be
public void CallAnotherFunction(string value, string content)
{
//do something
}
And I would like to pass content as part of the ForEach call
List<string> documents = GetAllDocuments();
documents.ForEach(CallAnotherFunction <<pass content>>);
List<string> templates = GetAllTemplates();
templates.ForEach(CallAnotherFunction <<pass another content>>);
Is there a way I can achieve this without having to define different functions, or use iterators?
Use lambda expressions instead of method groups:
List<string> documents = GetAllDocuments();
documents.ForEach( d => CallAnotherFunction(d, "some content") );
List<string> templates = GetAllTemplates();
templates.ForEach( t => CallAnotherFunction(t, "other content") );
Use lambda expression:
string content = "Other parameter value";
documents.ForEach(x => CallAnotherFunction(x, content));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With