Hooked on LINQ

Hooked on LINQ - Developers' Wiki
for .NET Language Integrated Query

Quick Search

Advanced Search »
There are two styles for writing LINQ queries, until this point we have been using the Query Expression syntax, but you need to understand both to fully utilize the query operators made available to you -

1. Query Expression format (preferred) See: Query Expression Syntax

int[] nums = new int[] {0,4,2,6,3,8,3,1};
 
var result = from n in nums
             where n < 5
             orderby n
             select n;


2. Extension Method format (also known as the Dot Notation syntax) See: Extension Method Syntax

int[] nums = new int[] {0,4,2,6,3,8,3,1};
 
var result = nums
             .Where(n => n < 5)
             .OrderBy (n => n);


Or when written on one line to better show Extension Methods at their best:

var result = nums.Where(n => n < 5).OrderBy (n => n);


3. A combination of the two formats, known as the Query Dot syntax. A Query Expression syntax query surrounded by parenthesis, followed by the dot notation Extension Method syntax. As long as the Query Expression returns an IEnumerable, it can be followed by an Extension Method chain.

int[] nums = new int[] {0,4,2,6,3,8,3,1};
 
var result = (from n in nums
              where n < 5
              orderby n
              select n).Distinct();


The Query Expression syntax has been designed to make writing queries more user-friendly and dare I say SQL like. The C# compiler converts all queries to use Extension Methods (although you don’t need to know that), so Query Expressions are solely there to make the developer experience that extra bit easier and it is a much cleaner syntax when you start to join and group.

My advice is use the Query Expression syntax wherever possible. I say “possible,” because the Query Expression syntax doesn’t support every Standard Query Operator currently available, and nor can it support any query operators you add over time. Drop back to the Query Dot syntax in those cases.

If you would like to comment on this page, click on the Discuss button located on the top-right of each page. Feel free to edit any mistakes or omissions you find. If you have an objection or find in-appropriate content then contact the administrator. This website is not affiliated with Microsoft®, all content and opinions are those of the specific author and some advice, solutions and article may contain unintentional errors - please use care. Powered by ScrewTurn Wiki version 2.0.33. Some of the icons created by FamFamFam.