使用 LINQ 更新集合中的所有对象 [英] Update all objects in a collection using LINQ
问题描述
有没有办法使用 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.
我的用例是我对一篇博文有很多评论,我想遍历一篇博文的每条评论,并将博文的日期时间设置为 +10 小时.我可以在 SQL 中完成,但我想将其保留在业务层中.
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.
推荐答案
虽然你可以使用 ForEach
扩展方法,但如果你只想使用框架,你可以这样做
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();
需要 ToList
以立即评估选择,因为延迟评估.
The ToList
is needed in order to evaluate the select immediately due to lazy evaluation.
这篇关于使用 LINQ 更新集合中的所有对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!