TOC

This article is currently in the process of being translated into Russian (~18% done).

LINQ:

Introduction

LINQ, сокращенное от Language-Integrated Query(язык интегрированных запросов), технология встроенная в .NET framework, которая позволяет легко обращаться и работать с данными из разных источников. Проще говоря, вы можете легко работать с различными данными, неважно это простой список, словарь , XML файл или таблица баз данных. LINQ существует в двух разновидностях: Запрос и синтаксис метода. В этой статье, мы тщательно изучим каждый из них, но чтобы заинтересовать вас изучить LINQ , позвольте мне быстро продемонстрировать как изящно LINQ может осуществлять запросы к простым данным:

var names = new List<string>()  
{  
    "John Doe",  
    "Jane Doe",  
    "Jenna Doe",  
    "Joe Doe"  
};  

// Get the names which are 8 characters or less, using LINQ  
var shortNames = from name in names where name.Length <= 8 orderby name.Length select name;

foreach (var name in shortNames)  
    Console.WriteLine(name);

In just one line, using the LINQ query syntax, I can ask for all names in the list which are 8 characters (or less) long and have them sorted by length! That's just ONE line of code and it only shows a small fraction of what LINQ is capable of! In the next articles, I will go through all the amazing possibilities you get when using LINQ, but first, we should talk a bit about how and when a LINQ query is executed.

Deferred execution

Most programmers are used to seeing the code being executed line after line, so it might come as a surprise to you that a LINQ query is not executed as soon as the line with the query part is hit. Instead, LINQ is executed as soon as you start using the data, e.g. when you iterate over it or call a method like ToList() or Count(). That also means that you can build a query over several lines, where you perform multiple operations, but the data is not actually fetched until you need it. Allow me to illustrate with an extended version of our previous example, where we switch to the method syntax instead of the previous query syntax:

var names = new List<string>()
{
    "John Doe",
    "Jane Doe",
    "Jenna Doe",
    "Joe Doe"
};

// Get the names which are 8 characters or less, using LINQ
var shortNames = names.Where(name => name.Length <= 8);
// Order it by length
shortNames = shortNames.OrderBy(name => name.Length);
// Add a name to the original list
names.Add("Zoe Doe");

// Iterate over it - the query has not actually been executed yet!
// It will be as soon as we hit the foreach loop though!
foreach (var name in shortNames)
    Console.WriteLine(name);

I have added some comments to the code, so it should be easy to follow. Also, notice that I have added a bit of proof in there: After doing the query, I add a name to the original list. Now, if the query had already been executed, this would of course not make it into the result, but it does, because it's added after the query but BEFORE we actually use the data, which happens in the foreach loop.

This is not of great importance when querying a list with 4 or 5 names, but imagine that instead, we had a list of 10 million entries or perhaps a remote database somewhere. In that case, it's very important that we don't execute multiple queries when we can just execute one query.

Summary

LINQ allows you to simply and natively query various data sources using the same syntax - either the query syntax or the method syntax, which we'll discuss in the next article.

This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!