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

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

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

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


当前回答

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

其他回答

没有内置的扩展方法可以做到这一点。尽管定义一个是相当简单的。在这篇文章的底部是我定义的一个叫做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来修改数据。使用循环。

这是我使用的扩展方法…

    /// <summary>
    /// Executes an Update statement block on all elements in an  IEnumerable of T
    /// sequence.
    /// </summary>
    /// <typeparam name="TSource">The source element type.</typeparam>
    /// <param name="source">The source sequence.</param>
    /// <param name="action">The action method to execute for each element.</param>
    /// <returns>The number of records affected.</returns>
    public static int Update<TSource>(this IEnumerable<TSource> source, Func<TSource> action)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (action == null) throw new ArgumentNullException("action");
        if (typeof (TSource).IsValueType)
            throw new NotSupportedException("value type elements are not supported by update.");

        var count = 0;
        foreach (var element in source)
        {
            action(element);
            count++;
        }
        return count;
    }

假设我们有如下数据,

var items = new List<string>({"123", "456", "789"});
// Like 123 value get updated to 123ABC ..

如果我们想修改列表并将列表中的现有值替换为修改后的值,那么首先创建一个新的空列表,然后通过调用每个列表项上的修改方法来遍历数据列表,

var modifiedItemsList = new List<string>();

items.ForEach(i => {
  var modifiedValue = ModifyingMethod(i);
  modifiedItemsList.Add(items.AsEnumerable().Where(w => w == i).Select(x => modifiedValue).ToList().FirstOrDefault()?.ToString()) 
});
// assign back the modified list
items = modifiedItemsList;

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