Is it safe to pass Linq and .ToList (),. Single (), etc. Another method as parameter func?

I needed to migrate some Linq queries using some Retry Policy logic.

Is it safe to pass:

return WithRetry<User>(() => 
   dataContext.Users.Where(u => u.UserID == userID).SingleOrDefault());

:

public TResult WithRetry<TResult>(Func<TResult> methodCall)
{ 
   // My Try/Catch Retry Code
}

Or the first line should be constructed as follows:

return WithRetry<User>(() => 
{ 
     return dataContext.Users
                       .Where(u => u.UserID == userID)
                       .SingleOrDefault(); 
});
+5
source share
2 answers

AFAIK, if the type of the argument is a method Func, its call will be automatically passed as a function without executing it. You do not need to additionally wrap it in an anonymous function wrapper.

+2
source

Anonymous wrapper is not needed. Just pass the lambda expression function call directly.

+3
source

All Articles