linq
  1. linq-filtering-data

Filtering Data with LINQ Query Syntax

One of the powerful features of LINQ Query Syntax is filtering data. We can filter data from collections or databases based on specific conditions using the where clause. In this tutorial, we will learn how to filter data using the where clause.

Syntax

var query = from element in collection
            where condition
            select element;

Example

Let's consider a simple collection of integers, numbers, and filter out only those numbers that are greater than 5.

int[] numbers = { 2, 5, 7, 9, 4, 8 };

var query = from num in numbers
            where num > 5
            select num;

In the above example, we are using the where clause to filter out only the numbers greater than 5 from the numbers collection.

Output

After executing the above query, the output will be:

7
9
8

Explanation

The where clause in the LINQ Query Syntax is used to filter data based on specific conditions. In the example above, we used the where clause to filter out only the numbers greater than 5 from the numbers collection.

Use

The where clause is a powerful tool for filtering data based on specific conditions. We can use it to filter data from collections, databases, and other data sources.

Important Points

  • The where clause returns a new collection that contains the filtered elements.
  • The condition used in the where clause can be any valid C# expression that evaluates to a boolean value.
  • We can use multiple where clauses to add additional conditions.

Summary

In this tutorial, we've learned how to filter data using the where clause in LINQ Query Syntax. We looked at a simple example where we filtered out only the numbers greater than 5 from a collection of integers. We've seen how the where clause works and how to use it to filter data from collections or databases. We also looked at some important points to keep in mind while filtering data with LINQ Query Syntax.

Published on: