LINQ
LINQ stands for Language Integrated Query. It is a data querying methodology that provides general purpose query capabilities to the .NET programming languages with similar syntax to SQL queries. LINQ provides query capability to multiple data sources such as LINQ query to databases, LINQ query to XML documents and LINQ query to in-memory objects such as arrays, lists, generic list and other collection types.
LINQ is the collection of extension methods for classes that implements IEnumerable and IQueryable interfaces, therefore the LINQ query is applicable to any object that implements the IEnumerable or IQueryable interface. LINQ provides a set of general purpose standard query operators used to perform different operations such as filter operation, groups operation, join operation, sorting operation, traversal operation, and projection operation on the elements of the collections or sequences. A collection or sequence is an object whose type implements IEnumerable<T> interface or IQueryable<T> interface. The IEnumerable<T> is a generic collection which is a base interface for the generic collections in the namespace System.Collections.Generic such as List<T>, LinkedList<T>, Queue<T>, Dictionary<T>, SortedList<T>, HashSet<T> etc. The <T> indicates the type of the collection.
The IEnumerable<T> is inherited from the base interface IEnumerable and IQueryable<T> is inherited from the base interface IQueryable. The LINQ is a structured query syntax built in C# and VB.NET that can be used to retrieve data from different data sources and from the collection of objects. When LINQ query is executed, it returns a new generic collection either IEnumerable<T> or IQueryable<T>, objects, or simple types. When LINQ query is used with the in-memory objects or with XML, it returns IEnumerable<T> collection and when LINQ query is used with the database then it returns the IQueryable<T> collection. Therefore, an object of IEnumerable<T> or IQueryable<T> interface is declared to receive the result of the LINQ query.
IEnumerable Interface
IEnumerable is a base interface for all the non-generic collections that can be enumerated. The IEnumerable interface is defined in the namespace System.Collections. The IEnumerable interface defines a single method GetEnumerator. The GetEnumerator method is used to return an object of the IEnumerator interface that iterates through a collection.
IEnumerator is the base interface for all the non-generic enumerators. The object of IEnumerator interface can be used with a for-each statement to read data in the collection. The IEnumerator interface defines two methods and one property. The methods are Reset() method and MoveNext() method and the property is Current property. The Reset() method is used to set the position of the IEnumerator before the first element of the collection. The MoveNext() method is used to move the IEnumerator to the next element of the collection. The Current property is used to get the current element of the collection.
The object of IEnumerator retrieves data as a read-only stream of data that does not allow modification. To get data from a collection, initially, the IEnumerator object is positioned before the first element in the collection or the Reset() method is used to bring the IEnumerator position before the first element in the collection then the MoveNext() method is used to advance or move the IEnumerator to the first element of the collection and the Current property is used to get the current element of the collection and then the MoveNext() method is used to move the IEnumerator to the next element of the collection and in this way the entire elements of the collection are retrieved.
IEnumerable<T> Interface
It is a base interface for all the generic collections defined in the namespace System.Collections.Generic such as List<T>, Queue<T>, Stack<T>, LinkedList<T>, Dictionary<T>, SortedList<T>, HashSet<T> etc. The IEnumerable<T> interface inherited from the IEnumerable interface. Therefore a type which implements the IEnumerable<T> interface will also implement members of the IEnumerable interface. The IEnumerable<T> interface defines a single method GetEnumerator which returns an object of the IEnumerator<T> interface.
IEnumerator<T> is the base interface for all the generic enumerators. The object of IEnumerator<T> interface can be used with a for-each statement to read data in the collection. The IEnumerator<T> interface defines a single property and three methods. The property is Current property and methods are Reset() method, MoveNext() method, and Dispose() Method. The Current property is used to get the element in the collection at the current position of the enumerator.
IQueryable Interface
IQueryable interface is used to evaluate queries against a specific data source in which the type of the data is not specified. IQueryable interface inherits IEnumerable interface and it returns IEnumerator interface that iterates through a collection. The IQueryable interface works same as an IEnumerable interface but the main difference is that IEnumerable interface provides a great functionality and achieves a good efficiency in case of disconnected or in-memory data sources or databases while IQueryable interface provides a great functionality and achieve a good efficiency in case of connected data sources or databases such as SQL etc. Therefore, if we work in in-memory data collections, the IEnumerable interface is the best choice and if we work in connected data sources or databases, the IQueryable interface is the best choice.
The IQueryable interface provides a single method GetEnumerator() and three properties such as ElementType, Expression, and Provider. The GetEnumerator() method is used to return the IEnumerator interface that iterates through a collection. The ElementType property is used to get the type of the elements. The elements are returned when the expression tree of the current instance of IQueryable is executed. The Expression property is used to get the expression tree associated with the instance of the IQueryable interface. The Provider property is used to get the query provider associated with the current data source.
LINQ Syntax
LINQ provides the following two general syntaxes,
- Query Expression Syntax
- Lambda Method Syntax
Query Expression Syntax
The Query Expression syntax is also called Query syntax. It starts with a From clause followed by a range variable and a collection from which we need to retrieve the data. The collection is either an IEnumerable<T> or IQueryable<T> collection. The structure of From clause is similar to a foreach loop. After the From clause, the Where clause is used followed by an expression that performs filter operations. The expression of Where clause contains the LINQ Query filtering operators to filter the data. After the expression of Where clause, the select or group by clause is used and followed by an expression to prepare the query result or the number of fields to be retrieved from the collection.
The LINQ Query Expression syntax always starts with the From clause followed by a range variable and ends with the select or group by clause. Following is the general syntax of LINQ Query Expression,
- <Query-Result> = From <Range-Variable> in <Collection>
- where <Expression> select or group by <Fields>
The <Query-Result> specifies the LINQ query variable that stores the LINQ query commands. The <Query-Result> is a generic collection either IEnumerable<T> or IQueryable<T>, objects, or simple types. The <Range-Variable> specifies a range variable of a collection, the <Collection> specifies a generic collection either IEnumerable<T> or IEQueryable<T> from which the data is to be retrieved, the “where” specifies Where clause which is used for the predicate or condition, the <Expression> specifies the filter operators of LINQ standard Query Operators to filter the data. The filters operators are used either in the form of SQL expression or using Lambda expression. The <Fields> specifies the number of fields to be retrieved from the collection or it may also be an expression that prepares the query result. To access the standard LINQ Query Operators, the namespace System.Query must be imported into the application or program.
Execution of LINQ Query Expression
The LINQ query expression cannot be executed directly but it needs an iterator to iterate the LINQ query variable. The foreach loop is usually used to iterate the LINQ query variable and retrieve the elements from the collection.
The following programming examples explain the LINQ query expression syntax,
Program # 1
Write a program that retrieves even numbers and a range of values from an integer array using LINQ query expression.
C# Program
- using System;
- using System.Linq;
- namespace ConsoleApplication1 {
- class Program {
- static void Main(string[] args) {
-
- int[] IntArray = new int[] {
- 3,
- 5,
- 7,
- 8,
- 9,
- 11,
- 16,
- 19,
- 23,
- 26
- };
-
-
- var EvenNum = from n in IntArray
- where n % 2 == 0 select n;
- foreach(var numbers in EvenNum) {
- Console.WriteLine(numbers);
- }
-
- var NumRange = from n in IntArray
- where(n > 8 && n < 23) select n;
- foreach(var numbers in NumRange) {
- Console.WriteLine(numbers);
- }
- Console.ReadKey();
- }
- }
- }
Visual Basic Program
- Module Module1
- Sub Main()
-
- 'Declare an integer array
- Dim IntArray As Integer() = {3, 5, 7, 8, 9, 11, 16, 19, 23, 26}
-
- 'LINQ Query to retrieve Even numbers from array
- Dim EvenNum As IEnumerable(Of Integer) = From n In IntArray
- Where n Mod 2 = 0
- Select n
-
- For Each numbers In EvenNum
- Console.WriteLine(numbers)
- Next
-
- 'LINQ Query to retrieve a range of values from array
- Dim NumRange As IEnumerable(Of Integer) = From n In IntArray
- Where (n > 8 And n < 23) Select n
-
- For Each numbers In NumRange
- Console.WriteLine(numbers)
- Next
-
- Console.ReadKey()
- End Sub
- End Module
Program # 2
Write a program that retrieves a different variety of elements from a String array.
C# Program
-
- string[] StringArray = {
- "one",
- "two",
- "three",
- "four",
- "five",
- "six",
- "seven",
- "eight",
- "nine",
- "ten"
- };
-
-
- IEnumerable < string > strLength = from str in StringArray
- where str.Length == 4
- select str;
- foreach(var str in strLength) {
- Console.WriteLine(str);
- }
-
-
- IEnumerable < string > strContains = from str in StringArray
- where str.Contains("i")
- select str;
- foreach(var str in strContains) {
- Console.WriteLine(str);
- }
Visual Basic Program
- 'Declare a String array
- Dim StringArray As String() = {
- "one",
- "two",
- "three",
- "four",
- "five",
- "six",
- "seven",
- "eight",
- "nine",
- "ten"
- }
- 'Retrieve those elements whose length are equal to four characters
- Dim strLength As IEnumerable(Of String) = From str In StringArray
- Where str.Length = 4
- Select str
- For Each s In strLength
- Console.WriteLine(s)
- Next
- 'Retrieve those elements whose contain character i
- Dim strContains As IEnumerable(Of String) = From str In StringArray
- Where str.Contains("i")
- Select str
- For Each s In strContains
- Console.WriteLine(s)
- Next
LINQ Method Syntax
Method syntax is also known as fluent syntax. The LINQ Method syntax uses extension methods for writing LINQ queries. LINQ provides various Extension methods such as where(), select(), orderby(), sum(), average() etc. Extension methods are defined in the namespace System.Linq and they implement IEnumerable<T> or IQueryable<T> interface. Each extension method of LINQ takes a Lambda expression as a predicate function as parameter.
The following programming examples explain the LINQ method syntax,
Program # 1
Write a program that retrieves even numbers and a range of values from an integer array using LINQ method syntax.
C# Program
-
- using System.Linq;
- using System.Collections.Generic;
-
- int[] IntArray = new int[] {
- 3,
- 5,
- 7,
- 8,
- 9,
- 11,
- 16,
- 19,
- 23,
- 26
- };
-
-
- IEnumerable < int > EvenNum = IntArray.Where(n => n % 2 == 0);
- foreach(var numbers in EvenNum) {
- Console.WriteLine(numbers);
- }
-
-
- IEnumerable < int > RangeNum = IntArray.Where(n => n > 8 && n < 23);
- foreach(var numbers in RangeNum) {
- Console.WriteLine(numbers);
- }
Visual Basic Program
- 'Include namespaces
- Imports System.Collections.Generic 'Declare an Integer Array
- Dim IntArray As Integer() = {
- 3,
- 5,
- 7,
- 8,
- 9,
- 11,
- 16,
- 19,
- 23,
- 26
- }
-
- 'LINQ Query to retrieve Even numbers from array
- Dim EvenNum As IEnumerable(Of Integer) = IntArray.Where(Function(n) n Mod 2 = 0)
- For Each number In EvenNum 'Console.WriteLine(number)
- Next
- 'LINQ Query to retrieve a range of values from array
- Dim RangeNum As IEnumerable(Of Integer) = IntArray.Where(Function(n) n > 8 And n < 23)
- For Each number In RangeNum
- Console.WriteLine(number)
- Next
Program # 2
Write a program that retrieves a different variety of elements from a String array using LINQ Method syntax.
C# Program
-
- using System.Linq;
- using System.Collections.Generic;
-
- string[] StringArray = {
- "one",
- "two",
- "three",
- "four",
- "five",
- "six",
- "seven",
- "eight",
- "nine",
- "ten"
- };
-
-
- var strLength = StringArray.Where(str => str.Length == 4);
- foreach(var str in strLength) {
- Console.WriteLine(str);
- }
-
-
- var strContains = StringArray.Where(str => str.Contains("i"));
- foreach(var str in strContains) {
- Console.WriteLine(str);
- }
Visual Basic Program
- 'Include namespaces
- Imports System.Collections.Generics;
- 'Declare a String Array
- Dim StringArray As String() = {
- "one",
- "two",
- "three",
- "four",
- "five",
- "six",
- "seven",
- "eight",
- "nine",
- "ten"
- }
-
- 'Retrieve those elements whose length are equal to four characters
- Dim strLength As IEnumerable(Of String) = StringArray.Where(Function(str) str.Length = 4)
- For Each s In strLength
- Console.WriteLine(s)
- Next
- 'Retrieve those elements whose contain character i
- Dim strContains As IEnumerable(Of String) = StringArray.Where(Function(str) str.Contains("i"))
- For Each s In strContains
- Console.WriteLine(s)
- Next