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.