How to: Write LINQ Queries in C#

This topic shows the three ways in which you can write a LINQ query in C#:

  1. Use query syntax.

  2. Use method syntax.

  3. Use a combination of query syntax and method syntax.

The following examples demonstrate some simple LINQ queries by using each approach listed previously. In general, the rule is to use (1) whenever possible, and use (2) and (3) whenever necessary.

Note

These queries operate on simple in-memory collections; however, the basic syntax is identical to that used in LINQ to SQL and LINQ to XML.

Example

Query Syntax

The recommended way to write most queries is to use query syntax to create query expressions. The following example shows three query expressions. The first query expression demonstrates how to filter or restrict results by applying conditions with a where clause. It returns all elements in the source sequence whose values are greater than 7 or less than 3. The second expression demonstrates how to order the returned results. The third expression demonstrates how to group results according to a key. This query returns two groups based on the first letter of the word.

// Query #1.
List<int> numbers = new List<int>() { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

// The query variable can also be implicitly typed by using var
IEnumerable<int> filteringQuery =
    from num in numbers
    where num < 3 || num > 7
    select num;

// Query #2.
IEnumerable<int> orderingQuery =
    from num in numbers
    where num < 3 || num > 7
    orderby num ascending 
    select num;

// Query #3. 
string[] groupingQuery = { "carrots", "cabbage", "broccoli", "beans", "barley" };
IEnumerable<IGrouping<char, string>> queryFoodGroups =
    from item in groupingQuery
    group item by item[0];

Note that the type of the queries is IEnumerable<T>. All of these queries could be written using var as shown in the following example:

var query = from num in numbers...

In each previous example, the queries do not actually execute until you iterate over the query variable in a foreach statement. For more information, see Introduction to LINQ Queries.

Method Syntax

Some query operations must be expressed as a method call. The most common such methods are those that return singleton numeric values, such as Sum, Max, Min, Average, and so on. These methods must always be called last in any query because they represent only a single value and cannot serve as the source for an additional query operation. The following example shows a method call in a query expression:

List<int> numbers1 = new List<int>() { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
List<int> numbers2 = new List<int>() { 15, 14, 11, 13, 19, 18, 16, 17, 12, 10 };
// Query #4. 
double average = numbers1.Average();

// Query #5.
IEnumerable<int> concatenationQuery = numbers1.Concat(numbers2);

If the method has parameters, these are provided in the form of a lambda expression, as shown in the following example:

// Query #6.
IEnumerable<int> largeNumbersQuery = numbers2.Where(c => c > 15);

In the previous queries, only Query #4 executes immediately. This is because it returns a single value, and not a generic IEnumerable<T> collection. The method itself has to use foreach in order to compute its value.

Each of the previous queries can be written by using implicit typing with var, as shown in the following example:

// var is used for convenience in these queries 
var average = numbers1.Average();
var concatenationQuery = numbers1.Concat(numbers2);
var largeNumbersQuery = numbers2.Where(c => c > 15);

Mixed Query and Method Syntax

This example shows how to use method syntax on the results of a query clause. Just enclose the query expression in parentheses, and then apply the dot operator and call the method. In the following example, query #7 returns a count of the numbers whose value is between 3 and 7. In general, however, it is better to use a second variable to store the result of the method call. In this manner, the query is less likely to be confused with the results of the query.

// Query #7. 

// Using a query expression with method syntax 
int numCount1 =
    (from num in numbers1
     where num < 3 || num > 7
     select num).Count();

// Better: Create a new variable to store 
// the method call result
IEnumerable<int> numbersQuery =
    from num in numbers1
    where num < 3 || num > 7
    select num;

int numCount2 = numbersQuery.Count();

Because Query #7 returns a single value and not a collection, the query executes immediately.

The previous query can be written by using implicit typing with var, as follows:

var numCount = (from num in numbers...

It can be written in method syntax as follows:

var numCount = numbers.Where(n => n < 3 || n > 7).Count();

It can be written by using explicit typing, as follows:

int numCount = numbers.Where(n => n < 3 || n > 7).Count();

See Also

Tasks

Walkthrough: Writing Queries in C# (LINQ)

Concepts

LINQ Query Expressions (C# Programming Guide)

Reference

where clause (C# Reference)

Other Resources

Language-Integrated Query (LINQ)