1.3 Queries
M extends LINQ query comprehensions with several features to make authoring simple queries more concise. The keywords, where and select are available as binary infix operators. Also, indexers are automatically added to strongly typed collections. These features allow common queries to be authored more compactly as illustrated next.
1.3.1 Filtering
Filtering extracts elements from an existing collection. Consider the following collection:
People { { First = "Mary", Last = "Smith", Age = 24 }, { First = "John", Last = "Doe", Age = 32 }, { First = "Dave", Last = "Smith", Age = 32 }, }
This query extracts people with Age == 32 from the People collection:
from p in People where p.Age == 32 select p
An equivalent query can be written with either of the following expressions:
People where value.Age == 32 People.Age(32)
The where operator takes a collection on the left and a Logical expression on the right. The where operator introduces a keyword identifier value into the scope of the Logical expression that is bound to each member of the collection. The resulting collection contains the members for which the expression is true. The expression:
Collection where Expression
is exactly equivalent to:
from value in Collection where Expression select value
Collection types gain indexer members that correspond to the fields of their corresponding element type. That is, this:
Collection . Field ( Expression )
is equivalent to:
from value in Collection where Field == Expression select value
1.3.2 Selection
Select is also available as an infix operator. Consider the following simple query:
from p in People select p.First + p.Last
This computes the select expression over each member of the collection and returns the result. Using the infix select it can be written equivalently as:
People select value.First + value.Last
The select operator takes a collection on the left and an arbitrary expression on the right. As with where, select introduces the keyword identifier value that ranges over each element in the collection. The select operator maps the expression over each element in the collection and returns the result. The expression:
Collection select Expression
Is exactly equivalent to:
from value in Collection select Expression
A trivial use of the select operator is to extract a single field:
People select value.First
Collections are augmented with accessors to fields that can be extracted directly. For example People.First yields a new collection containing all the first names, and People.Last yields a collection with all the last names.