---
description: Language-Integrated Query
---

# LINQ

{% embed url="https://learn.microsoft.com/en-us/dotnet/csharp/linq/" %}

The LINQ family of technologies provides a consistent query experience for objects (LINQ to Objects), relational databases (LINQ to SQL), and XML (LINQ to XML).

* LINQ is a uniform structured query syntax built in C# and VB.NET to retrieve data from different types of data sources and formats such as collections, ADO.Net DataSet, XML Docs, web service and MS SQL Server, and other databases.

![](https://1151231797-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MQAaqgCwmb83T8T0x2j%2F-MV-rFSE7oCbu7LqNzYd%2F-MV-spFTQzH99MdR3f2z%2Fimage.png?alt=media\&token=07c2fce7-a1a4-46aa-9f96-5774d8c717b8)

LINQ queries return results as objects. It enables you to uses object-oriented approach on the result set and not to worry about transforming different formats of results into objects.

### Advantages of LINQ

* **Familiar language:** Developers don’t have to learn a new query language for each type of data source or data format.
* **Less coding:** It reduces the amount of code to be written as compared with a more traditional approach.
* **Readable code:** LINQ makes the code more readable so other developers can easily understand and maintain it.
* **Standardized way of querying multiple data sources:** The same LINQ syntax can be used to query multiple data sources.
* **Compile time safety of queries:** It provides type checking of objects at compile time.
* **IntelliSense Support:** LINQ provides IntelliSense for generic collections.
* **Shaping data:** You can retrieve data in different shapes.

&#x20;LINQ queries uses extension methods for classes that implement `IEnumerable` or `IQueryable` interface. The `Enumerable` and `Queryable` are two static classes that contain extension methods to write LINQ queries.

&#x20;**Points to Remember:**

1. Use `System.Linq` namespace to use LINQ.
2. LINQ api includes two main static class Enumerable & Queryable.
3. The static Enumerable class includes extension methods for classes that implements the IEnumerable\<T> interface.
4. IEnumerable\<T> type of collections are in-memory collection like List, Dictionary, SortedList, Queue, HashSet, LinkedList.
5. The static Queryable class includes extension methods for classes that implements the IQueryable\<T> interface.
6. Remote query provider implements e.g. Linq-to-SQL, LINQ-to-Amazon etc.

<details>

<summary>Syntax</summary>

* Query Syntax Example

```csharp
var countries = new string[] { "India", "Japan", "USA", "UK" };

var result = from country in countries
                where country.Contains("a")
                select country;
```

* Method Syntax Example

```csharp
var countries = new List<string>() { "India", "Japan", "USA", "UK" };

var result = countries.Where(c => c.Contains('a'));
```

<pre class="language-csharp" data-title="output"><code class="lang-csharp">foreach(var i in result){
    Console.WriteLine(i);
}

<strong>/* 
</strong><strong>India
</strong><strong>Japan  
</strong><strong>*/
</strong></code></pre>

</details>

## Lambda Expression

{% code title="Anonymous Method in C#" %}
```
delegate(Student s) { return s.Age > 12 && s.Age < 20; };
```
{% endcode %}

{% code title="Lambda Expression in C#" %}
```
s => s.Age > 12 && s.Age < 20
```
{% endcode %}

**Q. Explain how LINQ is useful than Stored Procedures?**

* **Debugging:** It is difficult to debug a stored procedure but as LINQ is part of.NET, visual studios debugger can be used to debug the queries
* **Deployment:** For stored procedure, additional script should be provided but with LINQ everything gets compiled into single DLL hence deployment becomes easy
* **Type Safety:** LINQ is type safe, so queries errors are type checked at compile time

**System.Data.Dlinq.dll** provides the functionality to work with LINQ to SQL

**Q. Explain what is lambda expressions in LINQ?**\
Lambda expression is referred to as a unique function use to form delegates or expression tree types, where right side is the output and left side is the input to the method. For writing LINQ queries particularly, Lambda expression is used.

**Q. Mention what is the role of DataContext classes in LINQ?**\
DataContext class acts as a bridge between [SQL Server](https://www.guru99.com/sql-server-questions.html) database and the LINQ to SQL. For accessing the database and also for changing the data in the database, it contains connections string and the functions.

{% embed url="https://youtube.com/playlist?list=PLFO3wDtf0vUEnkbtNUvBynpsxRletwmQp" %}
