Lesson 36

LINQ to Objects

Lessons 34 and 35 explain how you can use Visual Studio's wizards to build simple database programs. They show one of many ways to connect a program to a data source.

Language-Integrated Query (LINQ) provides another method for bridging the gap between a program and data. Instead of simply providing another way to access data in a database, however, LINQ can help a program access data stored in many places. LINQ lets a program use the same techniques to access data stored in databases, arrays, collections, or files.

LINQ provides four basic technologies that give you access to data stored in various places:

  • LINQ to SQL—Data stored in SQL Server databases
  • LINQ to Dataset—Data stored in other databases
  • LINQ to XML—Data stored in XML (eXtensible Markup Language) files
  • LINQ to Objects—Data stored in collections, lists, arrays, strings, files, and so forth

In this lesson you learn how to use LINQ to Objects. You learn how to extract data from lists, collections, and arrays and how to process the results.

LINQ Basics

Using LINQ to process data takes three steps:

  1. Create a data source.
  2. Build a LINQ query to select data from the data source.
  3. Execute the query and process the result.

You might expect the third step to be two separate steps, “Execute the query” and “Process the result.” In practice, however, LINQ doesn't actually execute the query until it must—when the program tries to access the results. This is called deferred execution.

For example, ...

Get C# 24-Hour Trainer, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.