Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List Foreach parameterized delegate

Tags:

c#

generics

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?

like image 652
Srikanth Venugopalan Avatar asked Oct 24 '25 08:10

Srikanth Venugopalan


2 Answers

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") );
like image 124
nvoigt Avatar answered Oct 25 '25 22:10

nvoigt


Use lambda expression:

string content = "Other parameter value";
documents.ForEach(x => CallAnotherFunction(x, content));
like image 38
MarcinJuraszek Avatar answered Oct 25 '25 22:10

MarcinJuraszek