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.
While you can use a
ForEach
extension method, if you want to use just the framework you can doThe
ToList
is needed in order to evaluate the select immediately due to lazy evaluation.You can use LINQ to convert your collection to an array and then invoke Array.ForEach():
Obviously this will not work with collections of structs or inbuilt types like integers or strings.
I am doing this
Here is the extension method I use...
You can use Magiq, a batch operation framework for LINQ.