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:
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;
}
It's actually not linq, but you can try
users.ForEach(x => { x.CreateTime = DateTime.Now.AddMonths(-1);
x.LastUpdateTime = DateTime.Now; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With