在更新使用LINQ集合中的所有对象 [英] Update all objects in a collection using Linq

查看:216
本文介绍了在更新使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆