Here, we will learn about Linq query syntax and Linq method syntax with examples. The main advantage of Linq is that it allows us to write the query in the code itself due to which development becomes easier.

LINQ Syntax

Linq stands for Language Integrated Query and it is available in .NET version 3.5 or higher.

We can write Linq queries in two ways.

  • Query Syntax
  • Method Syntax

Linq Query Syntax:

It is quite different from standard SQL queries.

from <variablename> in <collection or table>
< where, grouping, operators, etc.> <lambda expression>
<groupBy operator or select> <format for results>

Order to be followed while writing LINQ queries. from will define the starting point of the Linq and is followed by user define variable followed by in after that the target collection or table name and followed by where clause if we want to apply some condition

ClauseDescription
From[Identifier]
In[Source Collection]
Let[Expression]
Where[Boolean Expression]
order by[Expression]
Select[Expression]
group by[Expression]
Into[Expression]
int[] numbers = { 10, 20, 30, 40, 50 };
IEnumerable<int> data = from num in numbers where num > 30 select num;

Example of Linq Query Syntax

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LinqDemoes
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = { 10, 20, 30, 40, 50 };
            IEnumerable<int> data = from num in numbers where num > 30 select num;
            foreach (var item in data)
            {
                Console.WriteLine(item);
            }
            Console.ReadLine();
        }
    }
}

Output:

40
50

Linq Method Syntax

It will use extension methods of Queryable or Enumerable static class.

int[] number = { 10, 20, 30, 40, 50 };
IEnumerable<int> result = number.Where(n => n > 20).ToList();

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LinqDemoes
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] number = { 10, 20, 30, 40, 50 };
            IEnumerable<int> result = number.Where(n => n > 20).ToList();
            foreach (var item in result)
            {
                Console.WriteLine(item);
            }
            Console.ReadLine();
        }
    }
}

Output:

30
40
50