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:27

My 2 pennies:-

 collection.Count(v => (v.PropertyToUpdate = newValue) == null);
查看更多
不再属于我。
3楼-- · 2019-01-01 10:28

Although you specifically asked for a linq-solution and this question is quite old I post a non-linq-solution. This is because linq (=lanuguage integrated query) is ment to be used for queries on collections. All linq-methods don´t modify the underlying collection, they just return a new one (or more precise an iterator to a new collection). Thus whatever you do e.g. with a Select doesn´t effect the underlying collection, you simply get a new one.

Of course you could do it with a ForEach (which isn´t linq, by the way, but an extension on List<T>). But this literally uses foreach anyway but with a lambda-expression. Apart from this every linq-method internally iterates your collection e.g. by using foreach or for, however it simply hides it from the client. I don´t consider this any more readable nor maintainable (think of edit your code while debugging a method containing lambda-expressions).

Having said this shoulnd´t use Linq to modify items in your collection. A better way is the solution you already provided in your question. With a classic loop you can easily iterate your collection and update its items. In fact all those solutuions relying on List.ForEach are nothing different but far harder to read from my perspective.

So you shouldn´t use linq in those cases where you want to update the elements of your collection.

查看更多
泪湿衣
4楼-- · 2019-01-01 10:28

I assume you want to change values inside a query so you could write a function for it

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

But not shure if this is what you mean.

查看更多
登录 后发表回答