Joe Cartano
Joe Cartano

Reputation: 3037

Combine Func<Foo, object> and Action<object>

I have a Func<Foo, object> and Action<object> and would like to combine these into Action<Foo>, which combines my Func and Action into one Action where the result of the Func is passed to the Action. Is there a straightforward way to do this?

Upvotes: 3

Views: 314

Answers (1)

dtb
dtb

Reputation: 217283

The most general method I can think of would be something like this:

Action<T1> Combine<T1, T2>(Func<T1, T2> func, Action<T2> action)
{
    return x => action(func(x));
}

Usage:

Func<Foo, object> func = x => x;
Action<object> action = Console.WriteLine;

Action<Foo> result = Combine(func, action);

result(new Foo());

Upvotes: 6

Related Questions