How can I pass a parameter in Action?

C#.NetAction

C# Problem Overview


private void Include(IList<string> includes, Action action)
{
    if (includes != null)
    {
        foreach (var include in includes)
            action(<add include here>);
    }
}

I want to call it like that

this.Include(includes, _context.Cars.Include(<NEED TO PASS each include to here>));

The idea is pass each include to the method.

C# Solutions


Solution 1 - C#

If you know what parameter you want to pass, take a Action<T> for the type. Example:

void LoopMethod (Action<int> code, int count) {
     for (int i = 0; i < count; i++) {
         code(i);
     }
}

If you want the parameter to be passed to your method, make the method generic:

void LoopMethod<T> (Action<T> code, int count, T paramater) {
     for (int i = 0; i < count; i++) {
         code(paramater);
     }
}

And the caller code:

Action<string> s = Console.WriteLine;
LoopMethod(s, 10, "Hello World");

Update. Your code should look like:

private void Include(IList<string> includes, Action<string> action)
{
    if (includes != null)
    {
         foreach (var include in includes)
             action(include);
    }
}

public void test()
{
    Action<string> dg = (s) => {
        _context.Cars.Include(s);
    };
    this.Include(includes, dg);
}

Solution 2 - C#

You're looking for Action<T>, which takes a parameter.

Solution 3 - C#

Dirty trick: You could as well use lambda expression to pass any code you want including the call with parameters.

this.Include(includes, () =>
{
    _context.Cars.Include(<parameters>);
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJopView Question on Stackoverflow
Solution 1 - C#The Scrum MeisterView Answer on Stackoverflow
Solution 2 - C#SLaksView Answer on Stackoverflow
Solution 3 - C#ne2dmarView Answer on Stackoverflow