Skip to content

LINQ Language Integrated Query

LINQ: LINQ stands for Language Integrated Query. It is a .NET feature that provides query expressions for retrieving and manipulating data from LINQ-enabled data sources.

LINQ defines a set of query operators that are used to query and filter data.

The difference between LINQ and SQL is that LINQ query expressions can work with many types of data, even data that is not in 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.
The LINQ to SQL provider converts a LINQ query to T-SQL that SQL Server can understand.
LINQ also provides IntelliSense and compile-time error checking.

LINQ architecture: LINQ to XML, LINQ to SQL and LINQ to Objects providers between queries and data sources

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.

LINQ queries can also sort and group the retrieved data. LINQ queries are written in a declarative query syntax, using clauses such as from, where, orderby and select. These are predefined clauses that we use to write a LINQ query.

The basic rule of LINQ query syntax is that a query expression must start with a from clause and end with a select or group clause.

To write LINQ queries, we use the LINQ standard query operators, such as Select, Where, OrderBy, Join and GroupBy.
There are two ways to write LINQ queries using these standard operators:
(1)- Using Lambda Expressions.
(2)- Using SQL-like query syntax.
The standard query operators are implemented as extension methods on the IEnumerable<T> interface.

Data Sources in LINQ Queries: The data source of a LINQ query can be a data structure, a web service, a file system, a database or an in-memory collection. Writing LINQ queries is simple because the syntax and pattern of the query do not change when the data source changes.
You can use LINQ with different data sources in these ways:
(1)- Implement the IEnumerable<T> interface to enable LINQ to Objects queries.
(2)- Create the standard query operator methods, such as Where and Select, to enable custom LINQ queries.

LINQ queries work independently of the data types and the structure of the original data source.

Standard Query Operators

The standard query operators are the methods that form the LINQ pattern. They are an API for querying any .NET array or collection. These operators provide query capabilities, including filtering, projection, aggregation and sorting.
The LINQ standard operators are classified into the following categories:

  • Aggregate Operators: Aggregate operators compute a single value from a collection. They include Aggregate, Average, Count, Sum, Min or MinBy, Max or MaxBy, and LongCount.
  • Filtering or Restriction Operators: The Where operator filters the result set based on specific conditions.
  • Projection Operators: They transform an object into a new form. Select, SelectMany and Zip are used for these kinds of operations.
  • Sorting Operators: They sort the items of a collection. They include OrderBy, OrderByDescending, ThenBy, ThenByDescending and Reverse.
  • Join Operators: They join two or more collections. They include Join and GroupJoin.
  • Grouping Operators: Grouping groups the data by common attributes. It includes GroupBy.
  • Quantifier Operators: They check a specific condition on the items and return a Boolean value. They include Any, All and Contains.
  • Partitioning Operators: Partitioning means dividing an input sequence into two sections, without rearranging the elements, and returning only one section. They include Take, TakeWhile, Skip and SkipWhile.
  • Set Operators: They compare elements of the same or different collections, based on the presence or absence of those elements, and return a result set. They include Distinct or DistinctBy, Union or UnionBy, Except or ExceptBy, and Intersect or IntersectBy.
  • Element Operators: They return a single, specific element from a sequence. They include ElementAt, ElementAtOrDefault, Single, SingleOrDefault, Last, LastOrDefault, First and FirstOrDefault .
  • Conversion Operators: They change the type of the input objects. They include AsEnumerable, AsQueryable, Cast, OfType, ToArray, ToDictionary, ToList and ToLookup.
  • Concatenation Operators: They append one sequence to another. There is only one: Concat.
  • Equality Operators: Two sequences are considered equal if they have the same number of elements and their corresponding elements are equal. It includes SequenceEqual.
  • Generation Operators: They generate a new sequence of values. They include DefaultIfEmpty, Empty, Range and Repeat.

Example code for the most commonly used methods

DefaultIfEmpty

internal class Program

   {

       static void Main(string[] args)

       {

           //Empty List of Integer values

           List<int> emptyList = new List<int>()

           {

           };

           //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<int> NumericList = new List<int>()

           {

               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