Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Daniel Solis - Illustrated C# 2010 - 2010.pdf
Скачиваний:
16
Добавлен:
11.06.2015
Размер:
11.23 Mб
Скачать

C H A P T E R 21

Introduction to LINQ

What Is LINQ?

LINQ Providers

Query Syntax and Method Syntax

Query Variables

The Structure of Query Expressions

The Standard Query Operators

LINQ to XML

537

CHAPTER 21 INTRODUCTION TO LINQ

What Is LINQ?

In a relational database system, data is organized into nicely normalized tables and accessed with a very simple but powerful query language—SQL. SQL can work with any set of data in a database because the data is organized into tables, following strict rules.

In a program, as opposed to a database, however, data is stored in class objects or structs that are all vastly different. As a result, there’s been no general query language for retrieving data from data structures. The method of retrieving data from objects has always been custom-designed as part of the program. LINQ, however, makes it easy to query collections of objects.

The following are the important high-level characteristics of LINQ:

LINQ stands for Language Integrated Query and is pronounced link.

LINQ is an extension of the .NET Framework that allows you to query collections of data in a manner similar to using SQL to query databases.

With LINQ you can query data from databases, collections of program objects, XML documents, and more.

The following code shows a simple example of using LINQ. In this code, the data source being queried is simply an array of ints. The definition of the query is the statement with the from and select keywords. Although the query is defined in this statement, it is actually performed and used in the foreach statement at the bottom.

 

static void Main()

 

 

 

{

 

 

 

int[] numbers = { 2, 12, 5, 15 };

// Data source

 

IEnumerable<int> lowNums =

// Define and store the query.

 

from n in numbers

 

 

 

where n < 10

 

 

 

select n;

 

 

 

foreach (var x in lowNums)

// Execute the query.

 

Console.Write("{0}, ", x);

 

 

 

}

 

 

 

This code produces the following output:

 

 

 

 

 

 

2,

5,

 

 

 

 

 

 

538

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]