Summary
Language Integrated Query (LINQ) is a new technology that allows you to query data sources from within your code, without needing to rely on specific data translation classes.
LINQ uses the same syntax with traditional databases, but also other data sources such as XML files, and even with collections in your application.
LINQ allows you to issue queries against collections in your code, returning a subset that’s easier to work with.
A LINQ data source collection must implement
IEnumerable
, and the collection the query returns must as well.The range variable is used to define the parameters of the query. It can be any valid C# name, and C# will automatically infer its type based on the returned values.
Once you have the enumerable collection of returned results, you can manipulate them as you would any generic collection.
You can use anonymous types and the
var
keyword in your queries to have the compiler infer the types in the query, whether simple or complex.You can use lambda expressions in your queries to define a method for evaluating the stored data, and then project the results onto a variable.
The
join
clause can unite the data from two different collections, but it has a special syntax, requiring the name of the collection to join with, the field you’re joining on in each collection, and the fields that should be in the return set.LINQ to SQL classes allows you to use the LINQ syntax to query a SQL database.
You need to include a reference to the
System.Data.Linq
namespace ...
Get Learning C# 3.0 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.