Conditionally update values in a List in C#

Google Translate Icon

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#.

Rate this post

Average rating 5/5. Vote count: 15

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

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

Tell us how we can improve this post?




Thanks for reading.

Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and help us grow. Happy coding :)



Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Do NOT follow this link or you will be banned from the site!