.NET Array Collections File String Async Cast Class Data Dictionary Enum Exception For Foreach IEnumerable If IndexOf Interface Lambda LINQ List Parse Path Process Property Regex Sort Split StringBuilder Substring Switch Time

LINQ: Language Integrated Query

LINQ. Imperative code describes how to complete an algorithm.
It proceeds step by step,
emphasizing process,
not result. Declarative code (like LINQ) describes the end result.

LINQ: keywords

This technology, Language Integrated Query, introduces extension methods. These work on Lists and arrays. We even use them on collections not yet in memory.

Example:We use the Average extension method to average all the elements in an int array. A double value is returned.

Tip:The Average method is implemented as an extension method within the .NET Framework. Extension methods have special syntax.

Extension Method
Based on:

.NET 4.5

C# program that uses LINQ extension

using System;
using System.Linq;

class Program
    static void Main()
	int[] array = { 1, 3, 5, 7 };



Convert. Some extension methods in LINQ convert from an IEnumerable to another type.
They convert to an array,
or Lookup.

Select method call

Mutate. These methods filter or mutate. They change the elements in your query in some way. We remove unneeded elements, add new ones, or change other aspects of the elements themselves.


Skip and take. These extension methods are useful. They eliminate the need for custom code to check ranges. Skip passes over the first elements.

Skip, SkipWhileTake, TakeWhile
Any method

Computation. LINQ also provides computational methods. These act upon a certain query and then return a number or other value. These can also simplify code.

Maximum and minimum values: height of buildings

Max and min. We can search a collection for its largest (max) or smallest (min) value. This is effective for many value types. Which tower is the tallest?

Max, Min

Enumerable. The Enumerable type has some useful static methods. If you need an IEnumerable collection of a range or a repeated element, consider Range or Repeat.

Empty:The Empty method returns an empty enumerable collection. This can be useful as a "dummy" value.


Range:The Range method provides an enumerable collection that progresses from one value to another.


Repeat:This method is repetitive—that is why it is called Repeat. It creates an enumerable collection full of one element.

Find icon

Query. A query expression uses declarative clauses. These specify the results we want, not how we are to achieve them. To start, we use a query expression on an array of integers.

Imperative:We describe how to accomplish the task by indicating each step in code statements.

Declarative:We describe the final result needed, leaving the steps up to the query language.

Descending: sort order

In the query, we select elements from an array in descending order (high to low). We filter out elements <= 2.
In the loop,
we evaluate the expression
and print the results.

C# program that uses query expression

using System;
using System.Linq;

class Program
    static void Main()
	int[] array = { 1, 2, 3, 6, 7, 8 };
	// Query expression.
	var elements = from element in array
		       orderby element descending
		       where element > 2
		       select element;
	// Enumerate.
	foreach (var element in elements)
	    Console.Write(' ');


8 7 6 3
Let contextual keyword

Keywords. Query expressions use a whole new set of keywords. These are contextual keywords. This means they only have meaning in query expressions.

ascendingdescendinggroupjoinletorderbyselect new

LINQ versus loop. LINQ has a performance cost. For small numeric operations, it introduces considerable overhead. For larger operations, this change is less important.

Benchmark:We count all elements in an array greater than or equal to 10 with LINQ and with a for-loop.

Result:The LINQ version is nearly ten times slower. For hot numeric loops, LINQ is a poor choice.

C# program that benchmarks LINQ, for-loop

using System;
using System.Diagnostics;
using System.Linq;

class Program
    const int _max = 1000000;
    static void Main()
	int[] values = { 10, 0, 1, 1, 20, 300, 400, 4 };

	// Version 1: use LINQ.
	var s1 = Stopwatch.StartNew();
	for (int i = 0; i < _max; i++)
	    int count = CountLinq(values);

	// Version 2: use for-loop.
	var s2 = Stopwatch.StartNew();
	for (int i = 0; i < _max; i++)
	    int count = CountFor(values);
	Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) /
	    _max).ToString("0.00 ns"));
	Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) /
	    _max).ToString("0.00 ns"));

    static int CountLinq(int[] values)
	// Count values greater than or equal to 10 with LINQ.
	return (from x in values
		where x >= 10
		select x).Count();

    static int CountFor(int[] values)
	// Count values greater than or equal to 10 with a loop.
	int count = 0;
	for (int i = 0; i < values.Length; i++)
	    if (values[i] >= 10)
	return count;


111.83 ns:    LINQ expression, Count()
 10.86 ns:    For-loop, if

Books. In query languages,
we express what we want,
not how it is to happen. The query language, not the programmer, is concerned with the exact implementation details.

We call this language the query language, because it is very useful for retrieving information from data bases by formulating queries, or questions, expressed in the language.

Structure and Interpretation of Computer Programs

LINQ is a powerful feature. Its methods and query expressions often improve the readability of programs.
And they sometimes lead to new,
superior algorithms.