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

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

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

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


当前回答

我的2便士:-

 collection.Count(v => (v.PropertyToUpdate = newValue) == null);

其他回答

你可以使用LINQ将你的集合转换为数组,然后调用array . foreach ():

Array.ForEach(MyCollection.ToArray(), item=>item.DoSomeStuff());

显然,这将不适用于结构体或内建类型(如整数或字符串)的集合。

不,LINQ不支持大规模更新。唯一更短的方法是使用ForEach扩展方法-为什么IEnumerable上没有ForEach扩展方法?

没有内置的扩展方法可以做到这一点。尽管定义一个是相当简单的。在这篇文章的底部是我定义的一个叫做Iterate的方法。它可以这样使用

collection.Iterate(c => { c.PropertyToSet = value;} );

遍历源

public static void Iterate<T>(this IEnumerable<T> enumerable, Action<T> callback)
{
    if (enumerable == null)
    {
        throw new ArgumentNullException("enumerable");
    }

    IterateHelper(enumerable, (x, i) => callback(x));
}

public static void Iterate<T>(this IEnumerable<T> enumerable, Action<T,int> callback)
{
    if (enumerable == null)
    {
        throw new ArgumentNullException("enumerable");
    }

    IterateHelper(enumerable, callback);
}

private static void IterateHelper<T>(this IEnumerable<T> enumerable, Action<T,int> callback)
{
    int count = 0;
    foreach (var cur in enumerable)
    {
        callback(cur, count);
        count++;
    }
}

有些人认为这是一种评论,但对我来说是一种回答,因为做错事的正确方法是不去做。所以,这个问题的答案就在问题本身。

不要使用LINQ来修改数据。使用循环。

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

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; }
}

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