Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

delegates

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?

like image 270
Joe Cartano Avatar asked Sep 12 '26 11:09

Joe Cartano


1 Answers

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());
like image 132
dtb Avatar answered Sep 13 '26 23:09

dtb