Can I update 2 fields using linq foreach loop at once?
Sample snippet :
I have a userdata with Name, Email, CreateTime, LastUpdateTime fields.
I have to reset CreateTime and LastUpdateTime for all users.
To update i am using 2 calls as below
users.ForEach(x => x.CreateTime= DateTime.Now.AddMonths(-1));
users.ForEach(x => x.LastUpdateTime = DateTime.Now);
instead can I do it in a single using linq foreach loop?
Well to start with, assuming this is
List<T>.ForEach, this isn’t using LINQ. But yes, you can create a lambda expression using a statement body:However, you may also want to use one consistent time for all the updates:
It’s not really clear why you want to achieve it this way though. I would suggest using a
foreachloop instead: