concept query expression in category c#

appears as: query expressions, query expression, The query expression, query expression, A query expression, query expressions
C# in Depth, Fourth Edition

This is an excerpt from Manning's book C# in Depth, Fourth Edition.

If you ask C# developers what they love about C#, they’ll likely mention LINQ. You’ve already seen some of the features that build up to LINQ, but the most radical is query expressions. Consider this code:

You may be wondering what all of this has to do with LINQ. I said that almost all the features in C# 3 built up to LINQ, so how do object and collection initializers fit into the picture? The answer is that other LINQ features require code to be expressible as a single expression. (For example, in a query expression, you can’t write a select clause that requires multiple statements to produce the output for a given input.)

The following listing shows the same query written as a query expression.

Listing 3.20. Introductory query expression with filtering, ordering, and projection
IEnumerable<string> query = from word in words
                            where word.Length > 4
                            orderby word
                            select word.ToUpper();


!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":0,\"ch\":28},{\"line\":0,\"ch\":46}],[{\"line\":1,\"ch\":28},{\"line\":1,\"ch\":49}],[{\"line\":2,\"ch\":28},{\"line\":2,\"ch\":40}],[{\"line\":3,\"ch\":28},{\"line\":3,\"ch\":49}]]"}
!@%STYLE%@!

The section of listing 3.20 in bold is the query expression, and it’s very concise indeed. The repetitive use of word as a parameter to lambda expressions has been replaced by specifying the name of a range variable once in the from clause, and then using it in each of the other clauses. What happens to the query expression in listing 3.20?

Query expressions work differently. The specification describes them as a syntactic translation that occurs before any overload resolution or binding. The code in listing 3.20 doesn’t just have the same eventual effect as listing 3.17; it’s really translated into the code in listing 3.17 before further processing. The language has no specific expectation about what the result of that further processing will be. In many cases, the result of the translation will be calls to extension methods, but that’s not required by the language specification. They could be instance method calls or invocations of delegates returned by properties named Select, Where, and so on.

The specification of query expressions puts in place an expectation of certain methods being available, but there’s no specific requirement for them all to be present. For example, if you write an API with suitable Select, OrderBy, and Where methods, you could use the kind of query shown in listing 3.20 even though you couldn’t use a query expression that includes a join clause.

Although we’re not going to look at every clause available in query expressions in detail, I need to draw your attention to two related concepts. In part, these provide greater justification for the language designers introducing query expressions into the language.

C# in Depth

This is an excerpt from Manning's book C# in Depth.

But if query expressions are no good, why does everyone make such a fuss about them, and about LINQ in general? The first answer is that although query expressions aren’t particularly beneficial for simple tasks, they’re very good for more complicated situations that would be hard to read if written out in the equivalent method calls (and would be fiendish in C# 1 or 2). Let’s make things a little harder by introducing another type—Supplier.

Figure 11.2. Sequence diagram of the execution of a query expression

The query expression is the part in bold. I’ve overridden ToString for each of the entities in the model, so the results of listing 11.1 are as follows:

User: Tim Trotter (Tester)
User: Tara Tutu (Tester)
User: Deborah Denton (Developer)
User: Darren Dahlia (Developer)
User: Mary Malcop (Manager)
User: Colin Carton (Customer)

You may be wondering how useful this is as an example; after all, you could just use SampleData.AllUsers directly in the foreach statement. But we’ll use this query expression—trivial though it is—to introduce two new concepts. First we’ll look at the general nature of the translation process the compiler uses when it encounters a query expression, and then we’ll discuss range variables.

Listing 11.2. The query expression of listing 11.1 translated into a method call
var query = SampleData.AllUsers.Select(user => user); foreach (var user in query) { Console.WriteLine(user); }

The C# 3 compiler translates the query expression into exactly this code before properly compiling it further. In particular, it doesn’t assume that it should use Enumerable .Select, or that List<T> will contain a method called Select. It merely translates the code and then lets the next phase of compilation deal with finding an appropriate method—whether as a straightforward member or as an extension method.[3] The parameter can be a suitable delegate type or an Expression<T> for an appropriate type T.

Real-World Functional Programming with Examples in F# and C#

This is an excerpt from Manning's book Real-World Functional Programming with Examples in F# and C#.

You may be thinking that you don’t use LINQ queries that often in your programs. This is definitely a valid point, because in imperative programs, LINQ queries are used less frequently. But functional programs do most of their data processing in the declarative style. In C#, they can be written using query expressions whereas F# provides higher-order list-processing functions (as we’ll see in chapters 5 and 6). This means that after you’ve read this book, you’ll be able to use declarative programming more often when working with data. As a result, your programs will be more easily parallelizable.

In C#, query expressions and iterators are quite different, but sequence expressions in F# show how they’re conceptually related. Each part of the query expression has an equivalent construct in F#, but it’s always more general: the from clause is replaced by a simple for loop, the where clause is replaced by an if condition, and the select clause corresponds to the yield statement with the projection expressed as a normal calculation.

12.4.1. Customizing query expressions

In principle, we can use queries to work with any type that supports the bind operation. This is the standard name used in functional programming for functions with type signatures of the form shown in the previous section. Technically speaking, we need to implement methods that are used by the C# compiler when translating the query expression into standard calls. We’ll implement these for the Option<T> type in section 12.6. The type doesn’t implement IEnumerable<T>, so the standard query operators can’t be used.

LINQ in Action

This is an excerpt from Manning's book LINQ in Action.

We will focus on LINQ to Objects, LINQ to SQL, and LINQ to XML in this book, but LINQ is open to new data sources. The three main LINQ providers discussed in this book are built on top of a common LINQ foundation. This foundation consists of a set of building blocks including query operators, query expressions, and expression trees, which allow the LINQ toolset to be extensible.

Until now, in this chapter, we’ve used a syntax based on method calls for our code samples. This is one way to express queries. But most of the time when you look at code based on LINQ, you’ll notice a different syntax: query expressions.

We’ll explain what query expressions are and then describe the relationship between query expressions and query operators.

Here is the same query with a query expression:

from book in SampleData.Books
where book.Title == "Funny Stories"
orderby book.Title
select new {book.Title, book.Price};

The two queries are equivalent. But you might notice that the query formulated with query operators makes extensive use of lambda expressions. Lambda expressions are useful, but too many in a small block of code can be unattractive. Also, in the same query, notice how the book identifier is declared several times. In comparison, in the query expression, you can see that the book identifier only needs to be declared once.

3.4.2. Writing query expressions

Let’s detail what query expressions look like in C# and in VB.NET.

Figure 3.3 shows the exhaustive syntax for a query expression.

Figure 3.3. C# query expression syntax

Let’s review how this syntax is presented in the C# 3.0 language specification. A query expression begins with a from clause and ends with either a select or group clause. The initial from clause can be followed by zero or more from, let, where, join, or orderby clauses.