Avoid using the let keyword in LINQ queries
You can use the let
keyword to declare a variable and assign it a value to use in your LINQ query if the value is to be used several times within the query. At first glance, this may seem like you are improving performance since you only perform a single assignment, and then use the same variable several times. But this is not actually the case. Using the let
keyword in your LINQ queries can actually decrease the performance of your LINQ query.
Let us work through some benchmark examples. In the LinqPerformance
class, do the following:
- Add the
ReadingDataWithoutUsingLet()
method:[Benchmark] public void ReadingDataWithoutUsingLet() { var result = from person in _people where person.LastName.Contains("Omega") && person.FirstName.Equals("Upsilon") select person; }
In this method, we are selecting people from the _people
list...