C# LINQ Examples: System.Linq and Extensions

Use extension methods, and query syntax, from the System.Linq namespace.
LINQ. The bird calls out in search of a mate. It queries the surrounding area with its bird song. With LINQ we formulate queries in our programs.
In a query, we ask for something. We ask for an array to be filtered or sorted or changed. LINQ is Language Integrated Query. System.Linq is useful in many programs.
Average example. LINQ introduces many extension methods. We use one (Average) 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.

Important: We include the System.Linq namespace with a "using" statement at the top. The program will not compile if we omit this.

C# program that uses LINQ extension using System; using System.Linq; class Program { static void Main() { int[] array = { 1, 3, 5, 7 }; Console.WriteLine(array.Average()); } } Output 4
Extension methods. This is a special syntax form in C#. We can call a method on a variable like it is an instance method. But it is not on the class. It is specified in a separate place.Extension

Linq: Extension methods are not part of LINQ. But they are essential in the understanding of this feature.

And: Things like "orderby" are transformed into extension method calls like OrderBy that act on sequences IEnumerables.

C# program that uses extension method static class ExtensionMethods { public static int MultiplyByTwo(this int value) { // This extension method multiplies an int by 2. return value * 2; } } class Program { static void Main() { // Use our extension method. System.Console.WriteLine(4.MultiplyByTwo()); } } Output 8
Convert. Some extension methods in LINQ convert from an IEnumerable to another type. They convert to an array, Dictionary, List or Lookup.ToArrayToDictionaryToListToLookup
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.AsEnumerableAsParallelAsQueryableCastConcatContainsDefaultIfEmptyDistinctElementAtElementAtOrDefaultExceptFirstFirstOrDefaultGroupByGroupJoinIntersectJoinLastLastOrDefaultOfTypeOrderByOrderByDescendingReverseSelectSelectManySingleSingleOrDefaultUnionWhereZip
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
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.AggregateAllAnyAverageCountSequenceEqualSum
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.

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.

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.Var
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(element); Console.Write(' '); } Console.WriteLine(); } } Output 8 7 6 3
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); } s1.Stop(); // Version 2: use for-loop. var s2 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { int count = CountFor(values); } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.Read(); } 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) { count++; } } return count; } } Output 111.83 ns: LINQ expression, Count() 10.86 ns: For-loop, if
An error. For queries to compile in the C# compiler we must include System.Linq at the top of the file. This is not optional. Visual Studio will provide a helpful error message.

Tip: Please add "using System.Linq" to fix this program. Compile-time errors are there to help us not make us mad.

C# program that causes System.Linq error class Program { static void Main() { int[] numbers = { 10, 20, 30 }; // We need to include System.Linq for this to work. var result = from n in numbers select n; } } Output Error CS1935 Could not find an implementation of the query pattern for source type 'int[]'. 'Select' not found. Are you missing a reference to 'System.Core.dll'
Syntactic sugar. LINQ can be seen as a form of syntactic sugar. Queries could be written with for-loops. But when a program is easier to read and write, often it is better.
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.

Quote: 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, delayed, superior algorithms.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Dot Net Perls