Common LINQ Operations
Filter collections and sort the output using LINQ queries.
We'll cover the following...
Basic syntax
All LINQ queries have nearly identical structures:
var result = from item in collection
select item;
- The
collectionis a collection object (like an array or list). - The
itemrefers to an individual element of that collection. - The
selectstatement is used to choose what should be returned as a result.
This is the basic syntax. It can be extended from here through filtering, sorting, projection, and so on. We’ll explore these operations individually.
Filter
To select items that match some criteria, we use the where clause. After the where keyword, we provide a boolean expression that determines how the filtering occurs:
Order the output
We use the orderby and orderby descending clauses to sort the resulting collection:
Projection
So far, we’ve been selecting whole items from the collection. In the previous lesson, we fetched Employee objects from the List<Employee> collection. Projection is customized selection. Instead of returning whole objects, we can choose what properties we want to select and encapsulate them inside either a different class or an anonymous type.
The let operator
We can also use the let keyword to perform some operations and store the results in temporary variables:
Multiple sources
It’s also possible to query several collections simultaneously. This can yield all possible combinations:
Method syntax
Using the query syntax isn’t the only way to harness the power of LINQ. We can achieve the same results using the extension methods, which we can call on any object that implements the IEnumerable interface. These extension methods become available as soon as we connect to the System.Linq namespace. For instance, the where clause of the query syntax translates to the Where() method:
The Where() method accepts a delegate that takes an individual element of the collection and returns a bool value. In the code above, we supply an anonymous method that takes the number parameter (an individual element of the numbers collection) and returns an indicator of whether it’s divisible by two without any remainder.
Similar to the Where() method, there are OrderBy() and OrderByDescending() methods, among others.