update 2 fields using linq foreach
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; });