Writing LINQ Expressions

Learn about LINQ, its components, the concept of deferred execution, and LINQ extension methods.

Although we wrote a few LINQ expressions, they weren’t the focus, so we didn’t understand properly how LINQ works. Let’s now take time to properly understand LINQ expressions.

What makes LINQ?

LINQ has several parts; some are required, and some are optional:

  • Extension methods (required): These include examples such as Where, OrderBy, and Select. These are what provide the functionality of LINQ.

  • LINQ providers (required): These include LINQ to Objects for processing in-memory objects, LINQ to Entities for processing data stored in external databases and modeled with EF Core, and LINQ to XML for processing data stored as XML. These providers execute LINQ expressions in a way specific to different data types.

  • Lambda expressions (optional): These can be used instead of named methods to simplify LINQ queries, for example, for the conditional logic of the Where method for filtering.

  • LINQ query comprehension syntax (optional): These include C# keywords like from, in, where, orderby, descending, and select. These are aliases for some of the LINQ extension methods, and their use can simplify the queries we write, especially if we already have experience with other query languages, such as Structured Query Language (SQL).

When programmers are first introduced to LINQ, they often believe that LINQ query comprehension syntax is LINQ, but, ironically, that is one of the parts of LINQ that is optional.

Building LINQ expressions with the Enumerable class

The LINQ extension methods, such as Where and Select, are appended by the Enumerable static class to any type, known as a sequence, that implements IEnumerable<T>.

For example, an array of any type implements the IEnumerable<T> class where T is the type of item in the array. This means that all arrays support LINQ to query and manipulate them. All generic collections, such as List<T>, Dictionary<TKey, TValue>, Stack<T>, and Queue<T>, implement IEnumerable<T>, so they can be queried and manipulated with LINQ, too.

Extension method

Enumerable defines more than 50 extension methods, as summarized in the following table

Note: This table will be useful for us for future reference, but for now, we can briefly scan it to get a feel for what extension methods exist and come back later to review it properly.

Get hands-on with 1400+ tech skills courses.