C# LINQ

Array Class Collections File Keyword String .NET ASP.NET Cast Compression Data Delegate Directive Enum Exception If Interface LINQ Loop Method Number Process Property Regex Sort StringBuilder Struct Switch Time Windows WPF

LINQ: Language Integrated Query

Imperative code describes how to complete an algorithm step-by-step. Declarative code instead describes the end result of that algorithm. LINQ is a declarative syntax form. It makes some computational tasks easier.

Intro

LINQ (language integrated query) introduces extension methods. Some of these methods are more helpful than others. They 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

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

Program that uses LINQ extension: C#

using System;
using System.Linq;

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

Output

4

Convert

Convert

Some extension methods in LINQ convert from an IEnumerable to another type.
They convert to an array,
Dictionary,
List
or Lookup. These are some of the most commonly useful methods.

ToArrayToDictionaryToListToLookup

Mutate

Select method call

These methods filter or mutate one or more collections. 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.

AsEnumerableAsParallelCastConcatContainsDefaultIfEmptyDistinctElementAtElementAtOrDefaultExceptFirstFirstOrDefaultGroupByGroupJoinIntersectJoinLastLastOrDefaultOfTypeOrderByOrderByDescendingReverseSelectSelectManySingleSingleOrDefaultUnionWhereZipSkip

Skip and Take:These extension methods are particularly useful. They eliminate the need for custom code to check ranges.

Skip, SkipWhileTake, TakeWhile

Computation

Any method

LINQ also provides computational methods. These act upon a certain query and then return a number or other value. These can also simplify your code, by eliminating the requirement of computing values such as averages yourself.

AggregateAllAnyAverageCountSequenceEqualSum

Max and Min:You can search a collection for its largest (max) or smallest (min) value. This is effective for many value types.

Max, Min

Enumerable

Iterate

The Enumerable type presents some static methods that can be useful in certain situations. 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.

EmptySteps

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

Range

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

Repeat

Query

Find icon

Next we explore query expressions. Query expressions are built with declarative clauses that specify the results you want, not how you want to achieve them. This program uses a query expression on an in-memory array of integers.

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

Descending: sort order

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

In the query expression, we select all the elements from the array in descending order (high to low). We then filter out elements less than or equal to 2.
In the foreach-loop,
we evaluate the expression
and print the results.

Var
Program that uses query expression: C#

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

Let contextual keyword

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

ascendingdescendinggroupjoinletorderbyselect new

Language

Books

Query languages are used to simplify how programs are written. 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. Abelson & Sussman, p. 440

Summary

System.Linq namespace

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

Tip:With lazy evaluation, we delay expensive operations.
This yields more immediate results.

C#