Share via


Quick Intro to Query Expressions

[Table of Contents] [Next Topic]

Due to all the buzz about LINQ and the related products, most .NET developers have had some level of exposure to query expressions.  For the uninitiated, a query expression looks like the following:

This blog is inactive.
New blog: EricWhite.com/blog

Blog TOC

Sub Main()
Dim names() As String = _
{"Burke", "Connor", "Frank", "Everett", "Albert", _
"George", "Harris", "David"}

Dim expr As IEnumerable(Of String) = _
From s In names _
Where (s.Length = 5) _
Order By s _
Select s.ToUpper()

For Each item As String In expr
Console.WriteLine(item)
Next
End Sub

I met a developer who thought that only LINQ query expressions are queries.  However, this isn't true.  You can write queries using the method syntax.  Here is the same query:

Dim expr As IEnumerable(Of String) = names _
.Where(Function(s) s.Length = 5) _
.OrderBy(Function(s) s) _
.Select(Function(s) s.ToUpper())

Both styles are queries.  They operate on the names array.  Arrays implement IEnumerable(Of T), and the result of the queries is also IEnumerable(Of T), and in this particular case, IEnumerable(Of String).

So in this document, when we talk about queries, this is what we're talking about.

This tutorial shows both forms of queries, but I find myself often gravitating towards method syntax.

Also, if you fully understand method syntax, and you understand how query expressions are translated to method syntax, then it is easy to write your queries using query expressions.  It was helpful for me to learn how to compose queries using method syntax.

Furthermore, in some cases, you can't write your desired queries without using method syntax.  There are ways to use both types of syntax in a single query, or you can write the entire query using method syntax.  It's a matter of style.

[Table of Contents] [Next Topic] [Blog Map]