LINQ Language Integrated Query

LINQ :- LINQ stands for Language Integrated Query is a programming model of .NET Framework that is used to provide some Query Expressions for retrieving and manipulating data from LINQ enabled Data Source.

LINQ defines the set of query Operators which are used to query and filter the data.

The difference between LINQ and SQL is that the Query Expressions in LINQ can be used to interact with numerous types of data, even the data that does not belong to a Relational Database.

LINQ Provider is a component between the LINQ query and the actual data source, which converts the LINQ query into a format that the underlying data source can understand.
LINQ to SQL provider conerts a LINQ query to T-SQL that SQL server database can understand.
LINQ also provides intellisense and compile time error checking.

Image is not available

LINQ Queries:- A Query is an Expression that retrieves the requested data from a Data Source. A LINQ Query specifies the information that you want to retrieve from a data source.

LINQ queries can also perform some additional functionality such as Sorting and Grouping the retrieved data. The LINQ queries are written in declarative query syntax with various Clauses used into it are like From, Where, Orderby and Select Clauses. These are predefined Clauses that we can use for the execution of a LINQ Query.

The basic syntax of LINQ Query is that the LINQ Query expressions must starts with the From Clause and ends with the Select or the Group Clause.

To write LINQ Queries we use the LINQ standard Query Opeartors Select, From, Where, Orderby, Join, Group by etc.
There are two ways to write LINQ queries using these standard opeartors.
(1)- Using Lambda Expressions.
(2)- Using SQL Like Queries.
The standard query operators are implemented as Extension Methods on IEnumerable Interface.

Data Sources in LINQ Queries :- The Data Source in LINQ query can be a Data Structure, a Web Service, a File System, or Database or In-memory collections. The execution of LINQ queries are simple because the syntax and the pattern of the query do not change with change in data source.
The different ways in which you can use LINQ with different data sources are as follow :-
(1)- Implement the IEnumerable T Interface to enable the LINQ to Objects queryies.
(2)- Create the standard query opeartor methods such as Where and Select to enable custom LINQ queries.

The execution of LINQ queries is independent of data types of data and structure of original data source.

Standard Query Operators

The standard query operators are the methods that form the LINQ pattern. It is an API that enables querying of any .Net array or collections. These operators provides Query capabilities including Filtering, Projection Aggregation and Sorting.
LINQ standard Operators are classified into following Categories :-

  • Aggregate Operators :- Aggregate Operators are used for computing the items from a collection and returns a single value. It includes many methods that are Aggregate, Average,Count, Sum, Min or MinBy, Max or MaxBy, Longcount .
  • Filtering or Restriction Operators :- Where Clause is used as a Filtering opeartor in LINQ which is used to filter the result set on the basis of some specific conditions.
  • Projection Operators :- It is used for transforming an object into a new form. Select, SelectMany and Zip is used for these kind of operations.
  • Sorting Operators :- It is used for sort the collection items based on pattern. It includes OrderBy, OrderByDecending, ThenBy, ThenByDescending, Reverse.
  • Join Operators :- It is used for Join the two or more collections. It includes Join, GroupJoin.
  • Grouping Operators :- Grouping is used for grouping the data based on same attributes. It includes GroupBy Clause.
  • Quantifier Operators :- It is used for checking a specific condition on items and it will return a Boolean Value. It include Any, All, contains.
  • Partitioning Operators :- Partioning means dividing an input sequence into two sections, without rearranging the elements sequence and returna a only one section. It include Take, Takewhile, Skip, Skipwhile.
  • Set Operators :- It is used for checking some elements into the same or different colections based on the presence or absence of that elements and returns a result set. It includes Distinct or DistinctBy, Union or UnionBy, Except or ExceptBy, Intersect or IntersectBy.
  • Element Operators :- It returns a single, speciifc elemnets from a sequence. It includes ElementAt, ElementAtOrDefault, Single, SingleOrDefault, Last, LastOrDefault, First, firstOrDefault .
  • Conversion Operators :- It changes the type of Input objects. It includes AsEnumerable, AsQueryable, Cast, OfType, ToArray, ToDictionary, ToList, ToLookup.
  • Concatenation Operators :- To append one sequence to another and it has only one operator that is Concate operator.
  • Equality Operators :- Two sequences whose corresponding elements are equal and which have the same number of elements are considered equal. It include SequenceEqual.
  • Generation Operators :- Generate new sequence of values. It include DefaultIfEmpty, Empty, Range, Repeat.

Example Code on mostly used methods

DefaultIfEmpty

                
 internal class Program
    {
        static void Main(string[] args)
        {
            //Empty List of Integer values
            List emptyList = new List()
            {
            };
            //DefaultIfEmpty will set a default value 0 here
            foreach (int number in emptyList.DefaultIfEmpty())
            {
                Console.WriteLine("Default Value set by method when empty -"+number);
            }
            //DefaultIfEmpty will set a default value 100 here
            foreach (int number in emptyList.DefaultIfEmpty(100))
            {
                Console.WriteLine("Default Value provided by user when empty -"+number);
            }
            Console.ReadKey();
        }
    }        

Output of the program

                
Default Value set by method when empty -   0
Default Value provided by user when empty -100
               

Sum, Max, Min, Average, Count

                
 internal class Program
    {
        static void Main(string[] args)
        {
            List NumericList = new List()
            {
                12,34,56,67,12,2,45,67,89,90,234,45,66
            };
            Console.WriteLine("Sum of the elemets -" + NumericList.Sum());
            Console.WriteLine("Max in the elemets -"+ NumericList.Max());
            Console.WriteLine("Min of the elemets -" + NumericList.Min());
            Console.WriteLine("Average of the elemets -" + NumericList.Average());
            Console.WriteLine("count of the elemets -" + NumericList.Count());
            Console.ReadKey();
        }
    }        

Output of the program

                
Sum of the elemets -  819
Max in the elemets -  234
Min of the elemets -  2
Average of the elemets - 63
count of the elemets - 13
               

Image is not available

About the Author
Sudheer Singh Chouhan is a Software Engineer having Expertise in Development Design and Architecting the applications , Project Management , Designing Large Scale Databases in SQL Server since last 17 Years.
Skill Sets :- Microsoft .NET technologies like ASP.Net Core, Web API, LINQ, Web Forms, WinForms, SQL Server, EntityFramework, Design Patterns, Solid Principles, Microservices, AWS Cloud.