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
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
using System; using System.Linq; using System.Collections.Generic; class Student { public string name { get; set; } public decimal age { get; set; } public override string ToString() { return "[" + name + ", " + age + "]"; } } public class Example { public static void Main() { var list = new List<Student> { new Student{name = "Olivia", age = 10}, new Student{name = "Robert", age = 20}, new Student{name = "John", age = 15} }; foreach (var item in list.Where(x => x.name == "Robert")) { item.age = 18; } Console.WriteLine(String.Join(", ", list)); } } |
Output:
[Olivia, 10], [Robert, 18], [John, 15]
The foreach loop can be replaced with the ForEach()
method, as shown below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
using System; using System.Linq; using System.Collections.Generic; class Student { public string name { get; set; } public decimal age { get; set; } public override string ToString() { return "[" + name + ", " + age + "]"; } } public class Example { public static void Main() { var list = new List<Student> { new Student{name = "Olivia", age = 10}, new Student{name = "Robert", age = 20}, new Student{name = "John", age = 15} }; list.Where(x => x.name == "Robert").ToList() .ForEach(x => x.age = 18); Console.WriteLine(String.Join(", ", list)); } } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
using System; using System.Linq; using System.Collections.Generic; class Student { public string name { get; set; } public decimal age { get; set; } public override string ToString() { return "[" + name + ", " + age + "]"; } } public class Example { public static void Main() { var list = new List<Student> { new Student{name = "Olivia", age = 10}, new Student{name = "Robert", age = 20}, new Student{name = "John", age = 15} }; var result = list.Where(x => x.name == "Robert") .Select(x => { x.age = 18; return x; }); Console.WriteLine(String.Join(", ", result)); } } |
Output:
[Robert, 18]
That’s all about conditionally updating values in a list in C#.