LINQ in C#

LINQ means Language Integrated Query. It was introduced in .NET Framework 3.5 to query the data from different data sources such as collections, generics, XML documents, SQL databases, etc., in both C# and VB.NET based on our requirements.


Generally, the LINQ will add a rich, standardized query syntax in .NET programming languages. It will allow the developers to write SQL style queries within the code to interact with any type of data.


To perform LINQ related operations such as filtering, sorting, etc., on available data sources, we need to import the System.Linq namespace in our application. 


In LINQ, we can write the queries in two ways.


  • Using Query Syntax
  • Using Method Syntax

LINQ Query Syntax in C#

In LINQ, to write the queries using query syntax, the structure should be as shown below.


from <variable> in <collection>

<where, joining, grouping, operators etc.> <lambda expression>

<select or groupBy operator> <format the results>

We need to follow this structure while writing the queries in LINQ. To learn more about Query syntax, refer to LINQ Query Syntax.

LINQ Method Syntax in C#

In LINQ, the method syntaxes will use extension methods of Enumerable or Queryable static classes.


Following is the example of using LINQ method syntaxes in c#.


int[] Num = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
//LINQ Method Syntax to Print Numbers Greater than 3
IEnumerable result = Num.Where(n => n > 3).ToList();

To learn more about method syntaxes in LINQ, refer LINQ Method Syntax.


To learn more about LINQ in C#, refer step by step LINQ Tutorial.