是否有一种方法来做以下使用LINQ?

foreach (var c in collection)
{
    c.PropertyToSet = value;
}

为了澄清,我希望遍历集合中的每个对象,然后更新每个对象的属性。

我的用例是我在一篇博客文章上有一堆评论,我想迭代一篇博客文章上的每一条评论,并将博客文章上的datetime设置为+10小时。我可以用SQL来做,但我想把它保留在业务层。


当前回答

你可以使用Magiq,一个LINQ的批处理操作框架。

其他回答

我的2便士:-

 collection.Count(v => (v.PropertyToUpdate = newValue) == null);
collection.ToList().ForEach(c => c.PropertyToSet = value);

我正在做这个

Collection.All(c => { c.needsChange = value; return true; });

我假设您希望在查询中更改值,以便为其编写函数

void DoStuff()
{
    Func<string, Foo, bool> test = (y, x) => { x.Bar = y; return true; };
    List<Foo> mylist = new List<Foo>();
    var v = from x in mylist
            where test("value", x)
            select x;
}

class Foo
{
    string Bar { get; set; }
}

但如果你是这个意思,那就不是舒坦了。

虽然您可以使用ForEach扩展方法,但如果您只想使用框架,则可以这样做

collection.Select(c => {c.PropertyToSet = value; return c;}).ToList();

由于延迟求值,需要使用ToList来立即求值选择。