Update all objects in a collection using LINQ


Question

Is there a way to do the following using LINQ?

foreach (var c in collection)
{
    c.PropertyToSet = value;
}

To clarify, I want to iterate through each object in a collection and then update a property on each object.

My use case is I have a bunch of comments on a blog post, and I want to iterate through each comment on a blog post and set the datetime on the blog post to be +10 hours. I could do it in SQL, but I want to keep it in the business layer.

1
442
4/28/2016 11:30:43 AM

Accepted Answer

While you can use a ForEach extension method, if you want to use just the framework you can do

collection.Select(c => {c.PropertyToSet = value; return c;}).ToList();

The ToList is needed in order to evaluate the select immediately due to lazy evaluation.

763
6/2/2017 7:56:00 PM

collection.ToList().ForEach(c => c.PropertyToSet = value);

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon