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.
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);
我正在这样做
Collection.All(c => { c.needsChange = value; return true; });
链接地址: http://www.djcxy.com/p/51350.html
上一篇: 空值不能分配
下一篇: 使用LINQ更新集合中的所有对象