Compartir a través de


LINQ Queries

[This content is no longer valid. For the latest information on "M", "Quadrant", SQL Server Modeling Services, and the Repository, see the Model Citizen blog.]

If your query requirements are simple, it is easiest to use the selector or projector syntax. However for more complex queries it may be necessary to use the full LINQ query syntax. Even this syntax has some abbreviated available forms that are easier to write.

This topic first illustrates the syntax by showing how to write selector or projector queries and then addresses more complex queries.

The examples in this topic use the following type and extent declarations.

    type Person 
    {
        Id : Integer64 => AutoNumber();
        First : Text;
        Last : Text;
        Age : Integer32;
    } where identity Id;

    People : {Person*}
    {
      { First => "Mary", Last => "Smith", Age => 24},
      { First => "John", Last => "Doe", Age => 32 },
      { First => "Dave", Last => "Smith", Age => 32 },
      { First => "Dave", Last => "Jones", Age => 39 },
      { First => "Bob", Last => "Martin", Age => 53 },
    }

Selectors and Projectors in linq Syntax

The easiest LINQ queries to write are for selectors and projectors, and these show basic features of the LINQ syntax.

Selectors

There are several ways to write selector queries in LINQ that vary in terms of conciseness. Consider the following selector expression.

People.Age(32)

The most explicit syntax for this projector is the following code.

from p in People
where p.Age == 32
select p

Here is a shorter way to write the same thing.

People
where value.Age == 32

All three variations return the following result.

{
      { First => "John", Last => "Doe", Age => 32 },
      { First => "Dave", Last => "Smith", Age => 32 },
}

Projectors

Now consider the following projector.

People.First

This can be written as follows.

from p in People
select p.First

These expressions return the following result.

{ "Mary", "John", "Dave", "Dave, "Bob" }

Note the main differences from the selector LINQ syntax: the projector code specifies no where clause, and the object of the select clause is the field name being projected, rather than the collection as a whole.

More Complex Queries

One way to make a projector query more complex is to add field names to the result to be returned. The following code adds another field and concatenates it to the first one. For more information about the concatenation operator, see + Operator ("M" Reference).

from p in People
select p.First + p.Last

Another more complex query is a selector with additional selection criteria, as shown in the following code.

from p in People
where p.Age == 32
and p.Last == "Smith"
select p