Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update all objects in a collection using LINQ

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.

like image 672
lomaxx Avatar asked Dec 29 '08 22:12

lomaxx


People also ask

Should I use LINQ to update a list of items?

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.

Do LINQ methods always return a new collection of objects?

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.

Why can’t I change the underlying collection in a LINQ query?

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.

How to submit changes to the database using LINQ?

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 ();


2 Answers

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.

like image 122
Cameron MacFarland Avatar answered Oct 15 '22 13:10

Cameron MacFarland


collection.ToList().ForEach(c => c.PropertyToSet = value); 
like image 41
Ε Г И І И О Avatar answered Oct 15 '22 12:10

Ε Г И І И О