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.
Solution 1:
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.
Solution 2:
collection.ToList().ForEach(c => c.PropertyToSet = value);
Solution 3:
I am doing this
Collection.All(c => { c.needsChange = value; return true; });
Solution 4:
I actually found an extension method that will do what I want nicely
public static IEnumerable<T> ForEach<T>(
this IEnumerable<T> source,
Action<T> act)
{
foreach (T element in source) act(element);
return source;
}
Solution 5:
Use:
ListOfStuff.Where(w => w.Thing == value).ToList().ForEach(f => f.OtherThing = vauleForNewOtherThing);
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.