Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I needed to wrap some Linq queries with some Retry Policy logic.

Is it safe to pass this:

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

to this:

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

Or should the first line be constructed like this instead:

return WithRetry<User>(() => 
{ 
     return dataContext.Users
                       .Where(u => u.UserID == userID)
                       .SingleOrDefault(); 
});
like image 961
Vyrotek Avatar asked Mar 03 '11 04:03

Vyrotek


People also ask

How to Distinct using LINQ?

If you want to return distinct elements from sequences of objects of some custom data type, you have to implement the IEquatable<T> generic interface in the class. The following code example shows how to implement this interface in a custom data type and provide GetHashCode and Equals methods.

How to write simple LINQ query in c# net?

List<int> numbers = new() { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; // The query variables can also be implicitly typed by using var // Query #1. IEnumerable<int> filteringQuery = from num in numbers where num < 3 || num > 7 select num; // Query #2.

What is Distinct() in c#?

C# Linq Distinct() method removes the duplicate elements from a sequence (list) and returns the distinct elements from a single data source. It comes under the Set operators' category in LINQ query operators, and the method works the same way as the DISTINCT directive in Structured Query Language (SQL).


1 Answers

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

like image 198
dthorpe Avatar answered Sep 21 '22 20:09

dthorpe