Created
December 1, 2020 21:29
-
-
Save jfcarr/f1580e4d9214fc1935629c996b5ffc7a to your computer and use it in GitHub Desktop.
Update elements in a collection, using LINQ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace UpdateCollection | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
try | |
{ | |
var people = new List<Person>() | |
{ | |
new Person() { FirstName = "Robert", LastName = "Jones" }, | |
new Person() { FirstName = "William", LastName = "Smith" } | |
}; | |
Console.WriteLine("Before:"); | |
foreach (var person in people) Console.WriteLine($"\tHello, {person.FirstName} {person.LastName}!"); | |
people.Where(p => p.FirstName == "Robert").ToList().ForEach(x => x.FirstName = "Bob"); | |
people.Where(p => p.FirstName == "William").ToList().ForEach(x => x.FirstName = "Bill"); | |
Console.WriteLine("After:"); | |
foreach (var person in people) Console.WriteLine($"\tHello, {person.FirstName} {person.LastName}!"); | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine(ex.Message); | |
} | |
} | |
} | |
public class Person | |
{ | |
public string FirstName { get; set; } | |
public string LastName { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment