Update selected in-memory objects with a clear loop
Use LINQ to choose objects and an ordinary loop to change them. This makes the mutation and its execution time visible.
The approach below changes existing reference-type objects in memory. It does not issue an SQL update or persist a detached collection.
Select, then mutate
In a .NET console project's Program.cs, run:
var items = new List<Item> { new() { Selected = true }, new() { Selected = false } };
var selected = items.Where(x => x.Selected).ToList();
foreach (var item in selected) {
item.Color = "Red";
item.Selected = false;
}
Console.WriteLine($"Changed {selected.Count}; first color: {items[0].Color}");
public sealed class Item {
public bool Selected { get; set; }
public string Color { get; set; } = "Blue";
}
The output is Changed 1; first color: Red. Materializing the selected references makes the chosen set explicit before properties used by its predicate are changed.
Distinguish collection edits from database updates
Changing objects tracked by EF Core requires SaveChanges to persist them. A provider-supported ExecuteUpdate performs a database operation directly and bypasses the change tracker, so already tracked objects can become stale. Those are different operations from this loop.
For value types, changing a copied loop variable does not update the original collection element. Prefer an immutable projection into a new collection or update the original by index. Avoid mutating inside Select because deferred execution makes it easy to repeat or skip side effects unintentionally.
Official references


Author: Herman Schoenfeld