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.
There is no built-in extension method to do this. Although defining one is fairly straight forward. At the bottom of the post is a method I defined called Iterate. It can be used like so
Iterate Source
No, LINQ doesn't support a manner of mass updating. The only shorter way would be to use a
ForEach
extension method - Why there is no ForEach extension method on IEnumerable?Use:
I am not sure if this is overusing LINQ or not, but it has worked for me when wanting to update a specific items in the list for a specific condition.
I wrote some extension methods to help me out with that.
I am using it like this:
For reference the argument check:
I actually found an extension method that will do what I want nicely
I've tried a few variations on this, and I keep going back to this guy's solution.
http://www.hookedonlinq.com/UpdateOperator.ashx
Again, this is somebody else's solution. But I've compiled the code into a small library, and use it fairly regularly.
I'm going to paste his code here, for the off chance that his site(blog) ceases to exist at some point in the future. (There's nothing worse than seeing a post that says "Here is the exact answer you need", Click, and Dead URL.)