Home > Backend Development > C++ > How Can LINQ Efficiently Update Properties of a Collection in C#?

How Can LINQ Efficiently Update Properties of a Collection in C#?

DDD
Release: 2025-01-20 13:01:08
Original
586 people have browsed it

How Can LINQ Efficiently Update Properties of a Collection in C#?

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>
Copy after login

A purely LINQ-based approach achieves the same result:

<code class="language-csharp">collection.Select(c => { c.PropertyToSet = value; return c; }).ToList();</code>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template