English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

LINQ Introduction

LINQ (Language Integrated Query) is a unified query syntax in C# and VB.NET, used for retrieving data from different sources and formats. It is integrated into C# or VB, thus eliminating the mismatch between programming languages and databases and providing a single query interface for different types of data sources.

For example, SQL is a structured query language used for storing and retrieving data from databases. Similarly, LINQ is an integrated structured query syntax in C# and VB.NET, used for retrieving data from various data sources (such as collections, ADO.Net DataSet, XML Docs, web services, MS SQL Server, and other databases).   

LINQ queries return results as objects. It allows you to use object-oriented methods on the result set without worrying about converting results of different formats to objects.          

The following example demonstrates a simple LINQ query that retrieves all strings from an array containing 'a'.

// Data Source
string[] names = {"Bill", "Steve", "James", "Mohan"};
// LINQ Query 
var myLinqQuery = from name in names
                where name.Contains('a')
                select name;
    
// Query Execution
foreach(var name in myLinqQuery)
    Console.Write(name + " ");

In the above example, the string array named names is a data source. Below is the LINQ query assigned to the variable myLinqQuery.

from name in names
where name.Contains('a')
select name;

The above query uses LINQ query syntax. You will learn more about it in the 'Query Syntax' chapter.

Before executing a LINQ query, you will not get its result. LINQ queries can be executed in many ways, and here we use a foreach loop to execute the query stored in myLinqQuery. The foreach loop executes the query on the data source and gets the results, then iterates over the result set.

Therefore, every LINQ query must query some data source, whether it can be an array, collection, XML, or other database. After writing a LINQ query, it must be executed to obtain the result.

Learn why to use LINQ in the next chapter.