C# LINQ

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

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

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.

ToArrayToDictionaryToListToLookup
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.

AsEnumerableAsParallelCastConcatContainsDefaultIfEmptyDistinctElementAtElementAtOrDefaultExceptFirstFirstOrDefaultGroupByGroupJoinIntersectJoinLastLastOrDefaultOfTypeOrderByOrderByDescendingReverseSelectSelectManySingleSingleOrDefaultUnionWhereZip
Skip

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.

AggregateAllAnyAverageCountSequenceEqualSum
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
Iterate

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.

Empty

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
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:You describe how to accomplish the task by indicating each step in code statements.

Declarative:You 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.

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

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
Books

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. Abelson & Sussman, p. 440


Copyright

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.

C#