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.
With a classic loop you can easily iterate your collection and update its items. In fact all those solutions 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.
While the LINQ methods always return a new collection, they don't create a new set of objects: Both the input collection (customers, in my example) and the output collection (validCustomers, in my previous example) are just sets of pointers to the same objects.
This is because LINQ (= language integrated query) is meant 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.
You should write the query to select the rows to be changed, change them in a loop, and submit the changes to the database (if LINQ to SQL). var query = tickets.Where (ticket => ticket.Name == "Beach"); foreach (var item in query) item.Selected = true; // if LINQ to SQL context.SubmitChanges ();
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.
collection.ToList().ForEach(c => c.PropertyToSet = value);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With