Skip to content

Lesson 10. LINQ

kudriako edited this page Apr 4, 2019 · 1 revision

Lesson 10. LINQ.

Definition

LINQ is .NET Language-Integrated Query

The .NET Language-Integrated Query defines a set of general purpose standard query operators that allow traversal, filter, and projection operations to be expressed in a direct yet declarative way in any .NET-based programming language.

LINQ Arhitecture

"LINQ to Objects" refers to the use of LINQ queries with any IEnumerable or IEnumerable collection directly, without the use of an intermediate LINQ provider or API.

"LINQ to Datasets" makes it easier and faster to query over data cached in a DataSet object.

"LINQ to SQL" (DLINQ) provides a run-time infrastructure for managing relational data as objects. Replaced by Entity Framework

"LINQ to Entities" (Entity Framework) operates on the entity set ( DbSet type properties) to access the data from the underlying database.

"LINQ to XML" (XLINQ) provides the in-memory document modification capabilities of the Document Object Model (DOM)

"Parallel LINQ" is a parallel implementation of LINQ to Objects.

Lambda vs Query Syntax

var longWords = words.Where( w => w.length > 10);

var longwords = from w in words where w.length > 10;

Defferedand immediate execution execution

By default, LINQ uses deferred execution.

When we write a LINQ query, it doesn’t execute by itself. It executes, when we access the query results. In other words, execution of the query is deferred until the query variable is iterated over in a foreach loop.

Benefits of Deferred Execution

  • It avoids unnecessary query execution and hence improves performance.
  • Query construction and Query execution are decoupled, so we can create the LINQ query in several steps.
  • A deferred execution query is reevaluated when you re-enumerate – hence we always get the latest data.

Operators

Filtering operators

Where - Filter values based on a predicate function

OfType - Filter values based on their ability to be as a specified type

Join Operators

Join - The operator join two sequences on basis of matching keys

Group Join - Join two sequences and group the matching elements

Projection operators

Select - The operator projects values on basis of a transform function

SelectMany - The operator project the sequences of values which are based on a transform function as well as flattens them into a single sequence

Sorting operators

OrderBy - The operator sort values in an ascending order

OrderByDescending - The operator sort values in a descending order

ThenBy - Executes a secondary sorting in an ascending order

ThenByDescending - Executes a secondary sorting in a descending order

Reverse - Performs a reversal of the order of the elements in a collection

Groupoing operators

GroupBy - Organize a sequence of items in groups and return them as an IEnumerable collection of type IGrouping<key, element>

ToLookup - Execute a grouping operation in which a sequence of key pairs are returned

Conversions

AsEnumerable - Returns the input typed as IEnumerable

AsQueryable - A (generic) IEnumerable is converted to a (generic) IQueryable

Cast - Performs casting of elements of a collection to a specified type

ToArray - Forces query execution and does conversion of a collection to an array

ToDictionary - On basis of a key selector function set elements into a Dictionary<TKey, TValue> and forces execution of a LINQ query

ToList - Forces execution of a query by converting a collection to a List

Concatenation

Concat Two sequences are concatenated for the formation of a single one sequence.

Aggregations

Aggregate - Operates on the values of a collection to perform custom aggregation operation

Average - Average value of a collection of values is calculated

Count - Counts the elements satisfying a predicate function within collection

LongCount - Counts the elements satisfying a predicate function within a huge collection

Max - Find out the maximum value within a collection

Min - Find out the minimum value existing within a collection

Sum - Find out the sum of a values within a collection

Quantifier Operations

All - Returns a value ‘True’ if all elements of a sequence satisfy a predicate condition

Any - Determines by searching a sequence that whether any element of the same satisfy a specified condition

Contains - Returns a ‘True’ value if finds that a specific element is there in a sequence if the sequence doe not contains that specific element , ‘false’ value is returned

Partition Operations

Skip - Skips some specified number of elements within a sequence and returns the remaining ones

SkipWhile - Same as that of Skip with the only exception that number of elements to skip are specified by a Boolean condition

Take - Take a specified number of elements from a sequence and skip the remaining ones

TakeWhile - Same as that of Take except the fact that number of elements to take are specified by a Boolean condition

Generation Operations

DefaultIfEmpty - When applied to an empty sequence, generate a default element within a sequence

Empty - Returns an empty sequence of values and is the most simplest generational operator

Range - Generates a collection having a sequence of integers or numbers

Repeat - Generates a sequence containing repeated values of a specific length

Set Operations

Distinct - Results a list of unique values from a collection by filtering duplicate data if any

Except - Compares the values of two collections and return the ones from one collection who are not in the other collection

Intersect - Returns the set of values found t be identical in two separate collections

Union - Combines content of two different collections into a single list that too without any duplicate content

Equality

SequenceEqual - Results a Boolean value if two sequences are found to be identical to each other

Element Operations

ElementAt - Returns an element present within a specific index in a collection

ElementAtOrDefault - Same as ElementAt except of the fact that it also returns a default value in case the specific index is out of range

First - Retrieves the first element within a collection or the first element satisfying a specific condition

FirstOrDefault - Same as First except the fact that it also returns a default value in case there is no existence of such elements

Last - Retrieves the last element present in a collection or the last element satisfying a specific condition

LastOrDefault - Same as Last except the fact that it also returns a default value in case there is no existence of any such element

Single - Returns the lone element of a collection or the lone element that satisfy a certain condition

SingleOrDefault - Returns the lone element of a collection or the lone element that satisfy a certain condition

DefaultIfEmpty - Returns a default value if the collection or list is empty or null

IEnumerable vs IQueriable

IEnumerable - Exposes an enumerator, which supports a simple iteration over a non-generic collection.

IQueriable - Provides functionality to evaluate queries against a specific data source wherein the type of the data is not specified. The IQueryable interface is intended for implementation by query providers.