📜  linq where c# (1)

📅  最后修改于: 2023-12-03 15:02:41.452000             🧑  作者: Mango

LINQ Where in C#

Introduction

LINQ (Language Integrated Query) provides a querying capability to extract data from collections, arrays, or any other data sources. LINQ allows developers to write queries that are close to natural language using a variety of operators like Where(), Select(), Sum(), etc.

LINQ Where() is a filter operator that is used to retrieve elements from a collection based on a specified condition. In this article, we will discuss how to use the Where() operator in C#.

Syntax

The syntax for using the Where() operator is as follows:

var filteredList = sourceList.Where(element => condition);

Here, sourceList is the list from where elements are filtered, filteredList is the list that contains the filtered elements, element represents each element of sourceList, and condition is the expression that defines how to filter elements.

Example

Let's consider a simple example of a list that contains a few integers.

List<int> numbersList = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

Now, we can filter this list using the Where() operator to retrieve all the even numbers.

var filteredList = numbersList.Where(number => number % 2 == 0);

Here, we're filtering all the elements of the list by checking if they're even using the % operator. The filteredList will contain the following elements:

2, 4, 6, 8, 10
Conclusion

LINQ Where() is a powerful operator that helps in filtering elements from a collection based on a specific condition. It's an essential operator for querying data sources using LINQ. In this article, we've discussed how to use the Where() operator in C#.