Update multiple values in the list using LINQ with where condition C#

This gist helps you to write a LINQ query to update multiple values in the list using LINQ with where condition in C#.

First, you might have a question why LINQ? LINQ makes the code more readable so other developers can easily understand and maintain it. Also, LINQ help with Compile time safety of queries and provides type checking of objects at compile time.

Now come to the main point. Suppose I have Employee class as below and I want to update the salary of all employees having experience >2 years.

public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Salary { get; set; }
        public int Experience { get; set; }
    }

You can use foreach loop to update the value within the list like below:

List<Employee> employees = new List<Employee>();

Suppose the above list contains some records.

Here is the syntax to update the salary for the employee having experience >2 years.

foreach (var emp in employees.Where(e => e.Experience > 2))
            {
                emp.Salary += 1000;
            }

Another possible way to update the employee salary is using the LINQ query only.

var employeeWithUpdatedSalary =  employees.Where(e => e.Experience > 2).Select(x => { x.Salary += 1000; return x; }).ToList();

Using both methods you can easily edit any records within the list. The above query also works for a single record.

I hope this gist about the Update multiple values in the list using LINQ with where condition C# helps you.

Happy Coding.