From the course: .NET Essentials: Working with LINQ

The three types of query expressions - .NET Tutorial

From the course: .NET Essentials: Working with LINQ

The three types of query expressions

- [Instructor] In this chapter, we will look at query expressions. We'll learn how to write a query expression, we'll talk about the syntax, we'll look at the minimum required to create a successful query expression. We'll talk about the various clauses that you can have in a query expression. Mostly we'll focus on the select clause, and as we go through the course, we'll look at the other clauses. And I thought before we started, we should step back and review some principles we've talked about earlier in this course. And I'm looking at the three categories that I think you can define for query expression. First category, is you take incoming sequence, and you return a new sequence that contains the same element type. So for example, if you have an array of doubles, you return an array of doubles. If you have a list of strings, you return a list of strings. Same with any of your custom types. Lets say I have a product class, you have a list of products, you return a list of products. Now the elements are the same type, but you can also perform other actions on them. You can sort them, you can group them, you can filter them and so on. The second type of query expression, is one that takes a sequence and returns a new sequence containing a different type of element. Essentially, this is a transformation of one object into another type. For example, you'll have an array of integers, and you return an array of decimals. Or you've got a list of products, and you return a list of strings. For the third area, we take a sequence and we return a single value. Now in various programming languages, this goes by different names. In functional programming this is often called fold or reduce. In other languages that might be called an accumulator or an aggregate. Essentially you're taking 10 items in a list and you're performing some sort of calculation on them and building up a running total or running average, something like that. The principle here is that always returns a single value. So in LINQ we have min, which will look through a list of numbers and return the lowest number. Max does the opposite, finds the highest number, and sum and average, those are some examples here. Those are the basic principles. And as we go through this query expression, we'll see how you can write query expressions that return each of these areas.

Contents