Update all objects in a collection using LINQ

2019-01-01 09:56发布

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.

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.

15条回答
浮光初槿花落
2楼-- · 2019-01-01 10:19

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();

The ToList is needed in order to evaluate the select immediately due to lazy evaluation.

查看更多
泛滥B
3楼-- · 2019-01-01 10:21
collection.ToList().ForEach(c => c.PropertyToSet = value);
查看更多
查无此人
4楼-- · 2019-01-01 10:21

You can use LINQ to convert your collection to an array and then invoke Array.ForEach():

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

Obviously this will not work with collections of structs or inbuilt types like integers or strings.

查看更多
冷夜・残月
5楼-- · 2019-01-01 10:24

I am doing this

Collection.All(c => { c.needsChange = value; return true; });
查看更多
柔情千种
6楼-- · 2019-01-01 10:24

Here is the extension method I use...

    /// <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;
    }
查看更多
人间绝色
7楼-- · 2019-01-01 10:24

You can use Magiq, a batch operation framework for LINQ.

查看更多
登录 后发表回答