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.
My 2 pennies:-
Although you specifically asked for a linq-solution and this question is quite old I post a non-linq-solution. This is because linq (=lanuguage integrated query) is ment to be used for queries on collections. All linq-methods don´t modify the underlying collection, they just return a new one (or more precise an iterator to a new collection). Thus whatever you do e.g. with a
Select
doesn´t effect the underlying collection, you simply get a new one.Of course you could do it with a
ForEach
(which isn´t linq, by the way, but an extension onList<T>
). But this literally usesforeach
anyway but with a lambda-expression. Apart from this every linq-method internally iterates your collection e.g. by usingforeach
orfor
, however it simply hides it from the client. I don´t consider this any more readable nor maintainable (think of edit your code while debugging a method containing lambda-expressions).Having said this shoulnd´t use Linq to modify items in your collection. A better way is the solution you already provided in your question. With a classic loop you can easily iterate your collection and update its items. In fact all those solutuions relying on
List.ForEach
are nothing different but far harder to read from my perspective.So you shouldn´t use linq in those cases where you want to update the elements of your collection.
I assume you want to change values inside a query so you could write a function for it
But not shure if this is what you mean.