...

/

Advanced LINQ Techniques for Filtering and Simplification

Advanced LINQ Techniques for Filtering and Simplification

Learn about filtering entities, targeting a named method, and lambda expression.

Filtering entities with Where

The most common reason for using LINQ is to filter items in a sequence using the Where extension method. Let’s explore filtering by defining a sequence of names and then applying LINQ operations to it:

Step 1: In the project file, add an element to remove the System.Linq namespace from automatically being imported globally, as shown in the following markup:

Press + to interact
<ItemGroup>
<Using Include="System.Console" Static="true" />
<Using Remove="System.Linq" />
</ItemGroup>

Step 2: In Program.cs, attempt to call the Where extension method on the array of names, as shown in the following code:

Press + to interact
SectionTitle("Writing queries");
var query = names.W

Step 3: As we try to type the Where method, note that it is missing from the IntelliSense list of members of a string array, as shown in the figure:

Press + to interact
IntelliSense with the Where extension method missing
IntelliSense with the Where extension method missing

This is because Where is an extension method. It does not exist on the array type. To make the Where extension method available, we must import the System.Linq namespace. This is implicitly imported by default in new .NET 6 and later projects, but we removed it.

Step 4: In the project file, comment out the element that removed System.Linq, as shown in the following code:

Press + to interact
<!--<Using Remove="System.Linq" />-->

...