LINQ's let keyword

12/14/2023

LINQ comes in two flavors: Query Syntax and Method Syntax. Either can be used. However Query Syntax comes with the let keyword. This can be used to create code that is better organized more readable to programmers.

An example: Articles with Comment Counts

Here's a simple example: On my webpage here I have articles with comments. Ignoring that this could be done via an inner join, let's say we want articles with comment counts greater than 0, and ordered by comment count descending. Using let, we can store that comment count in a variable, and keep the rest of the LINQ statement simple to read:

var commentCountQuery = 
    from article in context.BlogArticles
    let commentCount = (/* code that produces comment counts/*)
    where commentCount > 0
    orderby commentCount descending
    select new { article.BlogArticleId, article.Header, commentCount };

I'm a huge fan of readable code. Although this can be written using Method Syntax, this code is easier to read, which makes it my preferred version.


Please register or login to add a comment.

Comments (displaying 1 - 1):
No comments yet! Be the first...


  • C#/.NET/Core
  • T-SQL
  • HTML/Javascript/jQuery
  • ASP.NET/MVC
  • .NET Core
  • ADO.NET/EF
  • WPF
  • Xamarin/MAUI
  • Windows 10
  • SQL Server 20xx
  • Android
  • XBox One
  • Skiing
  • Rock Climbing
  • White water kayaking
  • Road Biking