Skip to content
Related Articles
Open in App
Not now

Related Articles

How to Convert SQL to LINQ Query?

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 26 Nov, 2022
Improve Article
Save Article

A group of technologies known as Language-Integrated Query (LINQ) is built on the direct integration of query functionality into the C# language. The query expression is the component of LINQ that stands out the most to developers who write LINQ queries. The declarative query syntax is used to write query expressions. Filtering, ordering, and grouping can all be done on data sources using LINQ syntax with the least amount of code.

LINQ

 

Convert SQL To LINQ Query:

LINQ is just like the reversal of the SQL query. In LINQ, required fields are projected before the where clause, just like in a SQL query. However, a projection occurs at the conclusion when using LINQ.

Format of SQL and LINQ Query:

  • SQL Format:

SELECT

FROM

WHERE

  • LINQ Format:

FROM

WHERE

SELECT

Let’s take an introductory example for the conversion of SQL to LINQ:

Query in SQL Format:

SELECT *
FROM Customers
WHERE last_name = 'Robinson' AND country = 'UK';

 

Query in LINQ Format:

FROM Customers
WHERE last_name = 'Robinson' AND country = 'UK';
SELECT *

Let’s take another example of conversion of SQL to LINQ query using C# language:

SQL Query:

The query is about finding the names from the name table and from the records column whose name contains the letter ‘e’.

SELECT name FROM records WHERE CONTAINS('e');

 

Converting SQL query to LINQ in C#:

Example 1:

C#




using System;
using System.Linq;
  
public class GFG
{
    public static void Main()
    {
        // Data source Or Database
        string[] records = {"Rajesh", "Geeks", "Utkarsh"
          , "Aaditya", "Sourabhe"};
          
        // LINQ Query 
        var Linq_query =  from name in records
                           where name.Contains('e')
                            select name;
          
        // Query execution
        foreach (var name in Linq_query)
            Console.Write(name + " ");
    }
}


Output:

 

Difference Between SQL and LINQ:

                                               SQL                                                                                      LINQ                                                                                         
It is a domain-specific language used for programming and designing the data which is in RDBMS. It is the Microsoft .NET framework that adds native data query capabilities.
It is a Structured Query Language. It is a Language Integrated Query language.
It is composed of native data querying. It is used for retrieval, saving, and updating in the database.

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!