Introduction To LINQ And LINQ Syntaxes

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,

  1. <Query-Result> = From <Range-Variable> in <Collection>  
  2. 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

  1. using System;  
  2. using System.Linq;  
  3. namespace ConsoleApplication1 {  
  4.     class Program {  
  5.         static void Main(string[] args) {  
  6.             //Declare an integer array  
  7.             int[] IntArray = new int[] {  
  8.                 3,  
  9.                 5,  
  10.                 7,  
  11.                 8,  
  12.                 9,  
  13.                 11,  
  14.                 16,  
  15.                 19,  
  16.                 23,  
  17.                 26  
  18.             };
  19.   
  20.             //LINQ Query to retrieve Even numbers from array  
  21.             var EvenNum = from n in IntArray  
  22.             where n % 2 == 0 select n;  
  23.             foreach(var numbers in EvenNum) {  
  24.                 Console.WriteLine(numbers);  
  25.             }

  26.             //LINQ Query to retrieve a range of values from array  
  27.             var NumRange = from n in IntArray  
  28.             where(n > 8 && n < 23) select n;  
  29.             foreach(var numbers in NumRange) {  
  30.                 Console.WriteLine(numbers);  
  31.             }  
  32.             Console.ReadKey();  
  33.         }  
  34.     }  
  35. }  
Visual Basic Program

  1. Module Module1  
  2. Sub Main()  
  3.   
  4. 'Declare an integer array  
  5. Dim IntArray As Integer() = {3, 5, 7, 8, 9, 11, 16, 19, 23, 26}  
  6.   
  7. 'LINQ Query to retrieve Even numbers from array  
  8. Dim EvenNum As IEnumerable(Of Integer) = From n In IntArray  
  9.                                          Where n Mod 2 = 0  
  10.                                          Select n  
  11.   
  12. For Each numbers In EvenNum  
  13. Console.WriteLine(numbers)  
  14. Next  
  15.   
  16. 'LINQ Query to retrieve a range of values from array  
  17. Dim NumRange As IEnumerable(Of Integer) = From n In IntArray  
  18.                                           Where (n > 8 And n < 23) Select n  
  19.   
  20. For Each numbers In NumRange  
  21. Console.WriteLine(numbers)  
  22. Next  
  23.   
  24. Console.ReadKey()  
  25. End Sub  
  26. End Module  

 

Program # 2

Write a program that retrieves a different variety of elements from a String array.
 
C# Program
  1. //Declare a String array  
  2. string[] StringArray = {  
  3.     "one",  
  4.     "two",  
  5.     "three",  
  6.     "four",  
  7.     "five",  
  8.     "six",  
  9.     "seven",  
  10.     "eight",  
  11.     "nine",  
  12.     "ten"  
  13. };
  14.   
  15. //Retrieve those elements whose length are equal to four characters  
  16. IEnumerable < string > strLength = from str in StringArray  
  17. where str.Length == 4  
  18. select str;  
  19. foreach(var str in strLength) {  
  20.     Console.WriteLine(str);  
  21. }
  22.   
  23. //Retrieve those elements whose contain character i  
  24. IEnumerable < string > strContains = from str in StringArray  
  25. where str.Contains("i")  
  26. select str;  
  27. foreach(var str in strContains) {  
  28.     Console.WriteLine(str);  
  29.  
Visual Basic Program
  1. 'Declare a String array  
  2. Dim StringArray As String() = {  
  3.     "one",  
  4.     "two",  
  5.     "three",  
  6.     "four",  
  7.     "five",  
  8.     "six",  
  9.     "seven",  
  10.     "eight",  
  11.     "nine",  
  12.     "ten"  
  13. }

  14. 'Retrieve those elements whose length are equal to four characters  
  15. Dim strLength As IEnumerable(Of String) = From str In StringArray  
  16. Where str.Length = 4  
  17. Select str  
  18. For Each s In strLength  
  19. Console.WriteLine(s)  
  20. Next

  21. 'Retrieve those elements whose contain character i  
  22. Dim strContains As IEnumerable(Of String) = From str In StringArray  
  23. Where str.Contains("i")  
  24. Select str  
  25. For Each s In strContains  
  26. Console.WriteLine(s)  
  27. 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

  1. //Include namespaces  
  2. using System.Linq;  
  3. using System.Collections.Generic;  
  4. //Declare an Integer Array  
  5. int[] IntArray = new int[] {  
  6.     3,  
  7.     5,  
  8.     7,  
  9.     8,  
  10.     9,  
  11.     11,  
  12.     16,  
  13.     19,  
  14.     23,  
  15.     26  
  16. };
  17.   
  18. //LINQ Query to retrieve Even numbers from array  
  19. IEnumerable < int > EvenNum = IntArray.Where(n => n % 2 == 0);  
  20. foreach(var numbers in EvenNum) {  
  21.     Console.WriteLine(numbers);  
  22. }
  23.   
  24. //LINQ Query to retrieve a range of values from array  
  25. IEnumerable < int > RangeNum = IntArray.Where(n => n > 8 && n < 23);  
  26. foreach(var numbers in RangeNum) {  
  27.     Console.WriteLine(numbers);  
  28. }  
Visual Basic Program
  1. 'Include namespaces  
  2. Imports System.Collections.Generic 'Declare an Integer Array  
  3. Dim IntArray As Integer() = {  
  4.     3,  
  5.     5,  
  6.     7,  
  7.     8,  
  8.     9,  
  9.     11,  
  10.     16,  
  11.     19,  
  12.     23,  
  13.     26  
  14. }
  15.   
  16. 'LINQ Query to retrieve Even numbers from array  
  17. Dim EvenNum As IEnumerable(Of Integer) = IntArray.Where(Function(n) n Mod 2 = 0)  
  18. For Each number In EvenNum 'Console.WriteLine(number)  
  19. Next 

  20. 'LINQ Query to retrieve a range of values from array  
  21. Dim RangeNum As IEnumerable(Of Integer) = IntArray.Where(Function(n) n > 8 And n < 23)  
  22. For Each number In RangeNum  
  23. Console.WriteLine(number)  
  24. Next   

 

Program # 2

Write a program that retrieves a different variety of elements from a String array using LINQ Method syntax.

C# Program
  1. //Include namespaces  
  2. using System.Linq;  
  3. using System.Collections.Generic;  
  4. //Declare a String Array  
  5. string[] StringArray = {  
  6.     "one",  
  7.     "two",  
  8.     "three",  
  9.     "four",  
  10.     "five",  
  11.     "six",  
  12.     "seven",  
  13.     "eight",  
  14.     "nine",  
  15.     "ten"  
  16. };
  17.   
  18. //Retrieve those elements whose length are equal to four characters  
  19. var strLength = StringArray.Where(str => str.Length == 4);  
  20. foreach(var str in strLength) {  
  21.     Console.WriteLine(str);  
  22. }
  23.   
  24. //Retrieve those elements whose contain character i  
  25. var strContains = StringArray.Where(str => str.Contains("i"));  
  26. foreach(var str in strContains) {  
  27.     Console.WriteLine(str);  
  28. }  
Visual Basic Program
  1. 'Include namespaces  
  2. Imports System.Collections.Generics;  
  3. 'Declare a String Array  
  4. Dim StringArray As String() = {  
  5.     "one",  
  6.     "two",  
  7.     "three",  
  8.     "four",  
  9.     "five",  
  10.     "six",  
  11.     "seven",  
  12.     "eight",  
  13.     "nine",  
  14.     "ten"  
  15. }
  16.   
  17. 'Retrieve those elements whose length are equal to four characters  
  18. Dim strLength As IEnumerable(Of String) = StringArray.Where(Function(str) str.Length = 4)  
  19. For Each s In strLength  
  20. Console.WriteLine(s)  
  21. Next 

  22. 'Retrieve those elements whose contain character i  
  23. Dim strContains As IEnumerable(Of String) = StringArray.Where(Function(str) str.Contains("i"))  
  24. For Each s In strContains  
  25. Console.WriteLine(s)  
  26. Next  


Similar Articles