在更新使用LINQ集合中的所有对象对象、LINQ

2023-09-02 01:22:55 作者:丶七夏

有没有办法做到使用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.