In C#, the let
keyword in LINQ queries is a neat way to store intermediate results inside a query. It keeps your code clean, readable, and avoids repeated calculations.
How let
Works
let
allows you to define a temporary variable in your query that you can reuse later:
string[] words = { "one", "two", "three", "four", "five" };
var query =
from w in words
let length = w.Length
where length > 3
select new { Word = w, Length = length };
foreach (var item in query)
Console.WriteLine($"{item.Word} - {item.Length}");
Output:
three - 5
four - 4
five - 4
Notice how let
avoids repeating w.Length
and makes the query cleaner.
Practical Example: Finding Palindromes
string[] words = { "level", "world", "civic", "radar", "test" };
var query =
from w in words
let reversed = new string(w.Reverse().ToArray())
where w == reversed
select w;
foreach (var item in query)
Console.WriteLine(item);
Output:
level
civic
radar
Here, let
stores the reversed string so we can reuse it in the where
clause.
Why Use let
?
- Reduce Repetition: Calculate once, reuse multiple times.
- Improve Readability: Makes queries easy to understand.
- Easier Maintenance: Change logic in one place.
Quick Tip
let
is different from into
:
-
let
= temporary variable inside a query. -
into
= continue querying a grouped or joined result.
let
is a small feature with a big impact. Start using it in your LINQ queries for cleaner and more efficient C# code.
I’m Morteza Jangjoo and “Explaining things I wish someone had explained to me”
Top comments (0)