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

5
(5)

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.

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 5

No votes so far! Be the first to rate this post.

As you found this post useful...

Share this post on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?