As developers, we often come across scenarios where we need to filter a list of objects based on a specific property value. This is where LINQ (Language Integrated Query) comes into play. LINQ is a powerful feature in C# that allows us to query data from different data sources, including lists, arrays, databases, and XML documents.
In this article, we will explore how we can use LINQ to filter a list based on a property value. Let's consider a simple example where we have a list of employees and we want to filter out the employees who have a salary greater than $50,000.
First, let's define our Employee class with properties such as Name, Age, and Salary:
```html
class Employee
{
public string Name { get; set; }
public int Age { get; set; }
public int Salary { get; set; }
}
```
Next, we will create a list of employees and populate it with some sample data:
```html
List<Employee> employees = new List<Employee>();
employees.Add(new Employee { Name = "John", Age = 25, Salary = 60000 });
employees.Add(new Employee { Name = "Emily", Age = 30, Salary = 45000 });
employees.Add(new Employee { Name = "Mike", Age = 28, Salary = 80000 });
```
Now, let's use LINQ to filter our list and get only those employees who have a salary greater than $50,000:
```html
var filteredList = employees.Where(emp => emp.Salary > 50000);
```
In the above code, we are using the `Where()` method of LINQ to filter our list. The `Where()` method takes a lambda expression as a parameter, which specifies the condition for filtering. In this case, we are checking if the salary of an employee is greater than $50,000.
The `filteredList` variable now contains a filtered list of employees, which we can use for further processing. We can also use other LINQ methods such as `OrderBy()`, `Select()`, or `GroupBy()` to manipulate the data according to our needs.
It's worth noting that LINQ uses deferred execution, which means the query is not executed until we iterate over the result. In our case, the query will be executed when we loop through the `filteredList` variable.
Another important point to mention is that we can use LINQ to filter a list based on multiple conditions. For example, if we want to filter out the employees who are above 25 years old and have a salary greater than $50,000, we can do it as follows:
```html
var filteredList = employees.Where(emp => emp.Age > 25 && emp.Salary > 50000);
```
In this case, we are using the logical AND operator (`&&`) to combine two conditions.
In addition to filtering, LINQ also allows us to perform other operations such as sorting, grouping, and joining on our data. This makes LINQ a powerful tool for data manipulation and retrieval.
In conclusion, LINQ provides a simple and efficient way to filter a list based on a property value. It is a versatile feature that can be used in various scenarios, making our code more concise and readable. So the next time you need to filter a list, don't forget to leverage the power of LINQ.