LINQ Query Syntax and Method Syntax

Query syntax is like SQL like query syntax. Query syntax is easier to read and write than Method syntax. But Query syntax does not support all query operators of LINQ.

A query syntax must begin with a from clause. The from clause specify data source (sequence) from which we need to get the data. Data source must implement IEnumerable<T> interface. From clause also specify a range variable (element) that represents a single element in the data source sequence.

In the next line we specify query operators to filter or group the data and in the last line we specify select query operator to select required fields of the sequence.

We have created ist of Student collection variable named students. In line 30, we write a LINQ query to filter out student which name contains "J" character.

In the first line we specify a range variable s and a sequence students. In line 31 we write a where query operator. On the next of where query operator we have lambda expression to filter out range variable which starts with "J" character. In line 32 we write a select query operator which select only name property of range variable.

LINQ query always returns a list of items. To get the first item in the list we apply First query operator to result which gives us the first item in the list in line 34.

In line 30, Where is a query operator of LINQ. As students is a type of List class which implements IEnumerable<T> interface it is available to this variable. Below is the syntax of Where extension method.

static IEnumerable<S> Where<S>(Func<S, bool> predicate);

Where operator takes a Func delegate as parameter where Student is a parameter and bool is return type. In the predicate we write a lambda expression where w is a parameter and right side w.Name.Contains is the body of the method. Where operator is always used for applying filter to the list. In the above example, we specify a filter condition which select only those elements from sequence which name contains "J" character.

Output of where operator is passed to Select query operator. Below is the syntax of Select extension method.

static IEnuerable<T> Select<S,T>(Func<S, T> selector);

Select query operator takes a Func delegate in which Student is a parameter and string is a result type. We write a lambda expression which select the required property from the object.

Notes:

Query syntax is easier to read but Method syntax are more powerful way to writing queries.

Both syntax's does not support all query operators. Some operators are not supported by Query Syntax and some are not by Method Syntax.