This post will discuss how to conditionally update values in a list in C#.

The Enumerable.Where() method filters a sequence of values based on a predicate. It is available in System.Linq namespace. The following code example demonstrates how we can use the Where() method with a foreach loop to conditionally update values in a list. The solution in-place updates the age of Robert from 20 to 18.

Download  Run Code

Output:

[Olivia, 10], [Robert, 18], [John, 15]

 
The foreach loop can be replaced with the ForEach() method, as shown below:

Download  Run Code

Output:

[Olivia, 10], [Robert, 18], [John, 15]

 
Both above solutions in-place updates values in a list in C#. To leave the original list unchanged and return a new list with updated values, you can do like below:

Download  Run Code

Output:

[Robert, 18]

That’s all about conditionally updating values in a list in C#.