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.
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.
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.
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) {
- //Declare an integer array
- int[] IntArray = new int[] {
- 3,
- 5,
- 7,
- 8,
- 9,
- 11,
- 16,
- 19,
- 23,
- 26
- };
- //LINQ Query to retrieve Even numbers from array
- var EvenNum = from n in IntArray
- where n % 2 == 0 select n;
- foreach(var numbers in EvenNum) {
- Console.WriteLine(numbers);
- }
- //LINQ Query to retrieve a range of values from array
- var NumRange = from n in IntArray
- where(n > 8 && n < 23) select n;
- foreach(var numbers in NumRange) {
- Console.WriteLine(numbers);
- }
- Console.ReadKey();
- }
- }
- }
- 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
- //Declare a String array
- string[] StringArray = {
- "one",
- "two",
- "three",
- "four",
- "five",
- "six",
- "seven",
- "eight",
- "nine",
- "ten"
- };
- //Retrieve those elements whose length are equal to four characters
- IEnumerable < string > strLength = from str in StringArray
- where str.Length == 4
- select str;
- foreach(var str in strLength) {
- Console.WriteLine(str);
- }
- //Retrieve those elements whose contain character i
- IEnumerable < string > strContains = from str in StringArray
- where str.Contains("i")
- select str;
- foreach(var str in strContains) {
- Console.WriteLine(str);
- }
- '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
C# Program
- //Include namespaces
- using System.Linq;
- using System.Collections.Generic;
- //Declare an Integer Array
- int[] IntArray = new int[] {
- 3,
- 5,
- 7,
- 8,
- 9,
- 11,
- 16,
- 19,
- 23,
- 26
- };
- //LINQ Query to retrieve Even numbers from array
- IEnumerable < int > EvenNum = IntArray.Where(n => n % 2 == 0);
- foreach(var numbers in EvenNum) {
- Console.WriteLine(numbers);
- }
- //LINQ Query to retrieve a range of values from array
- IEnumerable < int > RangeNum = IntArray.Where(n => n > 8 && n < 23);
- foreach(var numbers in RangeNum) {
- Console.WriteLine(numbers);
- }
- '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
C# Program
- //Include namespaces
- using System.Linq;
- using System.Collections.Generic;
- //Declare a String Array
- string[] StringArray = {
- "one",
- "two",
- "three",
- "four",
- "five",
- "six",
- "seven",
- "eight",
- "nine",
- "ten"
- };
- //Retrieve those elements whose length are equal to four characters
- var strLength = StringArray.Where(str => str.Length == 4);
- foreach(var str in strLength) {
- Console.WriteLine(str);
- }
- //Retrieve those elements whose contain character i
- var strContains = StringArray.Where(str => str.Contains("i"));
- foreach(var str in strContains) {
- Console.WriteLine(str);
- }
- '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

Viknaraj ManogararajahPosted Jul 25, 2018, 10:39 AM
nice article and nicely explained
Farhan AhmedPosted Jul 24, 2018, 10:42 PM
Nice article. Can you please add LINQ to SQL
Mahesh ChandPosted Jul 24, 2018, 8:23 PM
Also let us know if the community can help you promoting your books or anything else?
Mahesh ChandPosted Jul 24, 2018, 8:22 PM
Welcome to C# Corner Adalat. Thank you for the article. We definitely don't have many experts on LINQ. Best
Jignesh KumarPosted Jul 24, 2018, 12:08 PM
Nice explanation