Skip to content

Instantly share code, notes, and snippets.

@jfcarr
Created December 1, 2020 21:29
Show Gist options
  • Save jfcarr/f1580e4d9214fc1935629c996b5ffc7a to your computer and use it in GitHub Desktop.
Save jfcarr/f1580e4d9214fc1935629c996b5ffc7a to your computer and use it in GitHub Desktop.
Update elements in a collection, using LINQ
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