Passing in an anonymous method/function as a parameter in C#
I have a method that needs to conditionally execute a method, something like this:
int MyMethod(Func<int> someFunction)
{
if (_someConditionIsTrue)
{
return someFunction;
}
return 0;
}
I want to be able to pass a Linq query in to MyMethod as someFunction:
int i = MyMethod(_respository.Where(u => u.Id == 1).Select(u => u.Ot开发者_JS百科herId));
How do I do this?
int i = MyMethod(() => _respository.Where(u => u.Id == 1).Select(u => u.OtherId));
As you can see, I've made the query into a lambda. You will have to do this because otherwise, your query will be executed just before calling MyMethod
(...and will introduce compile-time errors ;) ) and not while it executes.
A side note:
This return someFunction;
should be return someFunction();
.
Maybe it's a typo, but in MyMethod you need to actually call the function:
return someFunction();
And when calling it, you're calling the function directly. Instead you need to pass a lambda expression. Also, you seem to be passing in a Func<IEnumerable<int>>
; add Single()
, SingleOrDefault()
, First()
or FirstOrDefault()
:
int i = MyMethod(() => _respository.Where(u => u.Id == 1).Select(u => u.OtherId).SingleOrDefault());
精彩评论