Cheat Sheet

LINQ For Dummies

From LINQ For Dummies by John Paul Mueller

Language INtegrated Query (LINQ) is a feature of .NET Framework that expands your grasp well beyond things Microsoft. You can use LINQ to query just about anything by knowing essential operators along with a few additional query operators. If you get a little lost along the way, Microsoft offers a wealth of resources through its network, blogs, and forums.

Essential LINQ Operators

Language INtegrated Query (LINQ) uses an amazing array of operators. An operator is a special word that tells LINQ what kind of query to perform, such as checking whether two values are equal. Operators can run into the hundreds, but in most cases you'll perform the majority of tasks using only a few standard operators. Below is a list of essential LINQ operators.

Operator Description
from Defines the temporary object used to perform a query. Think of this operator as defining the individual element object from which you derive all other data for the query. For example, you choose what data will appear in the output and how that data is ordered based on the temporary variable. The from operator is the only one that must appear in every query you create.
in Defines the data source used to obtain the data. A data source can be any object supported by a data provider. The provider creates a connection between the data source and the LINQ query. For example, a data source can include an object such as a list box, an XML file, an SQL Server table, Active Directory, a Web service, or just about anything else you want to use to collect information. It's even possible to work directly with files on your hard drive using a LINQ query. A query may contain as many matching pairs of from and in operators as is needed to fully describe the data sources used in the query.
select Chooses the output information for the query. The simplest output is the same object you define using the from operator. However, a select operator can include calculated values, arrays of data, or individual object properties. The limiting factor in most cases is the functionality offered by the LINQ provider. All four of the default providers include the complete range of select operator behaviors. A query contains only one select operator and this operator must appear as the last operator in the query.
where Describes the conditions under which an element appears as part of the output. The where operator always requires a Boolean argument to define the output conditions. You can include as many where operators as needed to fully describe the output criteria. LINQ interprets the where operators in the order in which they appear in the query, so order is important. When a query doesn't work as anticipated, try changing the order of the where operators to better describe the output requirements. Use the debugger to help locate errors in the logical flow of where operators.
orderby Defines the order in which the output elements appear. The simplest orderby operator relies on the object you define using the from operator. However, an orderby operator can accept any statement that defines a logical ordering argument as input — normally numeric, alphabetical, symbol, or binary. You can use as many orderby operators as needed to fully describe the output order of the data. As with the where operator, LINQ interprets the orderby operator in the order in which it appears in the query. Consequently, the order of the orderby operators is important.
join and on Combines two or more data sources to create a composite view of the data. The data sources need not rely on the same providers. You can use as many join operators as required to fully describe all of the data sources used for a query. The on operator defines the criterion used to combine two data sources. Pair the join and on operators to create a complete data source.
let Creates a calculated value for use within the query. Calculated values make complex queries easier to formulate. In addition, you can pass a calculated value onto the caller to provide additional output information. In many cases, the let operator provides the means for passing data that LINQ won't ordinarily pass due to a naming conflict. You can use as many let operators as required to provide full query functionality, but you should limit the use of let to situations where a calculated value enhances query speed.

Exploring LINQ Standard Query Operator Groups

Using standard query operators makes working with Language INtegrated Query (LINQ) considerably easier. In many ways, you've probably already worked with simple query operators. For example, when you use the orderby keyword, you're using a query operator in the sorting group of standard query operators. When you use the where keyword, you're using another query operator, but this time it's in the filtering group.

Here's a list of standard query operator groups and where you can find additional information.

Group Group Description Included Operators Additional Information
Aggregation operations The aggregation operators all help you perform mathematical tasks with a data source. Aggregate, Average, Count, LongCount, Max, Min, and Sum Microsoft Developer Network: Aggregation Operations
Concatenation operations The sole concatenation operator lets you combine two sequences. Concat Microsoft Developer Network: Concatenation Operations
Converting data types Converting data types come in two forms: deferred and nondeferred. The deferred conversion operators convert the results of a query to a particular type as the code interprets the result set. The nondeferred conversion operators change the output of a query to a particular type. AsEnumerable, AsQueryable, Cast, OfType, ToArray, ToDictionary, ToList, and ToLookup Microsoft Developer Network: Converting Data Types
Element operations The element operators help you select a particular element in a sequence, even when you don't know any identifying information about that element, such as its name. ElementAt, ElementAtOrDefault, First, FirstOrDefault, Last, LastOrDefault, Single, and SingleOrDefault Microsoft Developer Network: Element Operations
Equality operations The sole equality operator helps you determine whether two sequences are equal (the number of elements and the content of each element are equal). SequenceEqual Microsoft Developer Network: Equality Operations
Filtering data The filtering operators help you exclude or include elements in a sequence based on specific criteria. OfType and Where Microsoft Developer Network: Filtering Data
Generation operations The generation operators create a new sequence based on the criteria you specify. DefaultIfEmpty, Empty, Range, and Repeat Microsoft Developer Network: Generation Operations
Grouping data The grouping operators help you sort data by a particular characteristic, such as the first letter in a group of strings. GroupBy and ToLookup Microsoft Developer Network: Grouping Data
Join operations The joining operators accept two or more sequences as input and create a single output sequence based on a specific join type and the join criteria. Join and GroupJoin Microsoft Developer Network: Join Operations
Partitioning data The partitioning operators help you section a sequence to locate specific information. Skip, SkipWhile, Take, and TakeWhile Microsoft Developer Network: Partitioning Data
Projection operations The projection operators create a new type based on the query you create. Select and SelectMany Microsoft Developer Network: Projection Operations
Quantifier operations The quantifier operators help you select elements based on specific criteria. You use these operators to determine whether none, one, or more than one elements meet the selected criteria. All, Any, and Contains Microsoft Developer Network: Quantifier Operations
Set operations The set operators create sets. Think of the set arithmetic you performed in school. Distinct, Except, Intersect, and Union Microsoft Developer Network: Set Operations
Sorting data The sorting operators help you put a sequence into a particular order. OrderBy, OrderByDescending, ThenBy, ThenByDescending, and Reverse Microsoft Developer Network: Sorting Data

Microsoft LINQ Resources

It's always helpful to know where you can go for additional information and tools and enhancements when creating your Language INtegrated Query (LINQ) applications. Here's a list of helpful Microsoft resources for LINQ.

Microsoft Developer Network

The Microsoft Developer Network (MSDN) has always provided the baseline material for all Microsoft development products. You'll find a whole warehouse of information there — more than any one human being can probably read in a lifetime. Consequently, you need to sift the information carefully or you'll quickly become lost in the MSDN labyrinth. The main MSDN site for working with LINQ provides you with news, resources, and access to other information such as samples.

Microsoft blogs

Microsoft wants you to know how to work with LINQ. In the past, you'd find much of the information you need on MSDN. The MSDN website is still a good place to go, but many Microsoft developers complained that it was a bit too formal (the articles are pretty difficult to understand in some cases) and there wasn't any opportunity to interact with the authors. The Microsoft blogs provide a friendlier environment for obtaining information where you can actually correspond with the author. Here are a few blogs you'll want to visit when working with LINQ:

Most of these blogs are generic — they all discuss programming issues of some kind. Consequently, you'll find a mix of topics in each blog. The author may discuss the file system in one post and LINQ on another. Each has LINQ-specific entries that you can search for using the search features on the blog. Although Charlie Calvert has left Microsoft, his blog contains a wealth of general LINQ information.

Microsoft forums

If you don't think that you're getting enough interaction with Microsoft through a blog, Microsoft employees often frequent the Microsoft forums as well. Uploading a message to the correct forum can net you some professional help or at least some knowledgeable help from another forum member. Most developers rely on the MSDN forum for basic questions about LINQ. You can see a general listing of forums at the Microsoft Community. Don't forget to try the language-specific forum for Visual Basic .NET.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com