Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update 2 fields using linq foreach

Tags:

c#

linq

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?

like image 897
Vinod Vutpala Avatar asked Jun 11 '12 09:06

Vinod Vutpala


2 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;
}
like image 85
Jon Skeet Avatar answered Nov 09 '22 20:11

Jon Skeet


It's actually not linq, but you can try

users.ForEach(x => { x.CreateTime = DateTime.Now.AddMonths(-1);
                     x.LastUpdateTime = DateTime.Now; });
like image 25
Vlad Avatar answered Nov 09 '22 21:11

Vlad