Thursday, September 20, 2007 12:12 AM
LINQ Line by Line (Part 2): the select clause
The Basics
The select clause ends a LINQ query expression. It determines what the evaluation of the query will give back when it is evaluated. The select clause is highlighted in yellow in the example below.
1 var query =
2 from person in GetPeople()
3 select person;
The Basic Select Clause
The select clause consists of the select keyword followed by an expresion.
The Expression
I have a simple way of thinking about an expression that holds true most of the time. An expression is anything that can be assigned to a variable. The candidates for this part of the select clause can be any expression: a number, string, new instance of a class, new instance of an anonymous class, an existing instance, a mathmatical expression, a boolean expression, and more. The word expression is a little confusing because a LINQ query itself is (by default) an _“Expression”_: an abstract representation of a query.
Example: Selecting a Member of a Class
1 var nameQuery =
2 from person in GetPeople()
3 select person.Name;
4
5 foreach (var name in nameQuery)
6 {
7 Console.WriteLine(“The name is {0}”, name);
8 }
Example: Selecting an Unrelated Expression
1 int n = 0;
2 var accQuery = from person in GetPeople()
3 select n++;
4
5 foreach (int acc in accQuery)
6 {
7 Console.WriteLine(“The number is {0}”, n);
8 }
The output of this little snippet is:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The interesting point of this example is that n doesn’t change values until the query is evaluated. Until then, the query only lives as an expression tree. The act of asking for the enumerator evaluates the query and n starts to be incremented each time MoveNext is called.
Transfiguration from Person to Rapper
var rapQuery =
from person in GetPeople()
select new
{
FirstName = person.FirstName,
RapName =
person.FirstName[0] +
person.LastName.Substring(0, 3)
.ToLowerInvariant()
};
foreach (var rapper in rapQuery)
{
Console.WriteLine(
”{0}, your rap name is: {1}”,
rapper.FirstName, rapper.RapName);
}
The output of this little snippet is:
John, your rap name is: Jdoe
Jane, your rap name is: Jfon
Jonah, your rap name is: Jwha
Jim, your rap name is: Jdea
Jasper, your rap name is: Junk
The Extras to be Used in Dinner Conversation
The simple example of a query expression, one that selects all elements in its sequence; without filtering, ordering, or grouping has a fancy name: a degenerate query. Basically, when the expression tree is evaluated it can be replaced by the original sequence. This comes in handy in a more complicated query expression as the degenerate query can be prunned from the tree.
Link to Linq
Please make sure you check out: 101 Linq Examples.
Tags: LINQ, C#