Blog - Title

Quick Intro to Query Expressions

Quick Intro to Query Expressions

  • Comments 2

[Blog Map]  [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 (also attached to this page):

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

Blog TOC
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
class Program
{
    static void Main(string[] args)
    {
        string[] names = { "Burke", "Connor", "Frank",
                   "Everett", "Albert", "George",
                   "Harris", "David" };
 
        IEnumerable<string> expr = from s in names
                                   where s.Length == 5
                                   orderby s
                                   select s.ToUpper();
 
        foreach (string item in expr)
            Console.WriteLine(item);
    }
}
 

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 (also attached to this page):

IEnumerable<string> expr = names
                           .Where(s => s.Length == 5)
                           .OrderBy(s => s)
                           .Select(s => s.ToUpper());
 

Both styles are queries.  They operate on the names array.  Arrays implement IEnumerable<T>, and the result of the queries is also IEnumerable<T>, and in this particular case, IEnumerable<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.

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

Attachment: QuickIntroToQueryExpressions.cs
Leave a Comment
  • Please add 1 and 5 and type the answer here:
  • Post
  • This is a tutorial on using Functional Programming (FP) techniques for constructing LINQ queries. It is certainly possible to write simple LINQ queries without using these techniques, but as soon as you start writing more complicated queries, you need

  • [Table of Contents] [Next Topic] Perhaps the best way to compare and contrast the imperative (stateful)

Page 1 of 1 (2 items)