...
/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:
<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:
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:
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:
<!--<Using Remove="System.Linq" />-->
...