Optimizing C# Collection Updates with LINQ
LINQ offers efficient methods for modifying properties across a collection of objects. While the ForEach
extension method provides a loop-like syntax:
<code class="language-csharp">collection.ForEach(c => c.PropertyToSet = value);</code>
A purely LINQ-based approach achieves the same result:
<code class="language-csharp">collection.Select(c => { c.PropertyToSet = value; return c; }).ToList();</code>
Crucially, ToList()
forces immediate execution, overcoming LINQ's inherent lazy evaluation.
Consider a practical example: updating the timestamp of blog comments. To add 10 hours to each comment's DateAdded
property within the business layer:
<code class="language-csharp">var comments = _context.Comments.Where(c => c.BlogPostId == blogPostId); comments.Select(c => { c.DateAdded = c.DateAdded.AddHours(10); return c; }).ToList(); _context.SaveChanges();</code>
This LINQ approach streamlines the update process, eliminating the need for direct SQL manipulation and neatly integrating data modification into your business logic.
The above is the detailed content of How Can LINQ Efficiently Update Properties of a Collection in C#?. For more information, please follow other related articles on the PHP Chinese website!