update 2 fields using linq foreach

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?

Answers


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:

users.ForEach(x => {
    x.CreateTime = DateTime.Now.AddMonths(-1);
    x.LastUpdateTime = DateTime.Now;
});

However, you may also want to use one consistent time for all the updates:

DateTime updateTime = DateTime.Now;
DateTime createTime = updateTime.AddMonths(-1);

users.ForEach(x => {
    x.CreateTime = createTime;
    x.LastUpdateTime = updateTime;
});

It's not really clear why you want to achieve it this way though. I would suggest using a foreach loop instead:

DateTime updateTime = DateTime.Now;
DateTime createTime = updateTime.AddMonths(-1);

foreach (var user in users)
{
    user.CreateTime = createTime;
    user.LastUpdateTime = updateTime;
}

See Eric Lippert's blog post on foreach vs ForEach for more thoughts on this.


It's actually not linq, but you can try

users.ForEach(x => { x.CreateTime = DateTime.Now.AddMonths(-1);
                     x.LastUpdateTime = DateTime.Now; });

Need Your Help

How do I persist a value accross views

c# .net asp.net-mvc

Completely new to asp.net mvc... completely new to web apps so bear with me...

What are some good Entity Framework Alternatives

c# sql orm

I am using the Entity Framework now and constantly having to write inline sql because Entity framework does not support full text search and other features. Is there a ORM out there that has many