C# 使用 linq foreach 更新 2 个字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10977237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
update 2 fields using linq foreach
提问by Vinod Vutpala
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.
我可以一次使用 linq foreach 循环更新 2 个字段吗?示例片段:我有一个包含名称、电子邮件、创建时间、上次更新时间字段的用户数据。我必须为所有用户重置 CreateTime 和 LastUpdateTime。
To update i am using 2 calls as below
要更新我正在使用 2 个电话,如下所示
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?
相反,我可以使用 linq foreach 循环一次完成吗?
采纳答案by Jon Skeet
Well to start with, assuming this is List<T>.ForEach, this isn'tusing LINQ. But yes, you can create a lambda expression using a statement body:
首先,假设这是List<T>.ForEach,这不是使用 LINQ。但是是的,您可以使用语句主体创建 lambda 表达式:
users.ForEach(x => {
x.CreateTime = DateTime.Now.AddMonths(-1);
x.LastUpdateTime = DateTime.Now;
});
However, you may alsowant 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 whyyou want to achieve it this way though. I would suggest using a foreachloop instead:
不过,目前还不清楚为什么要以这种方式实现它。我建议改用foreach循环:
DateTime updateTime = DateTime.Now;
DateTime createTime = updateTime.AddMonths(-1);
foreach (var user in users)
{
user.CreateTime = createTime;
user.LastUpdateTime = updateTime;
}
回答by Vlad
It's actually not linq, but you can try
它实际上不是 linq,但您可以尝试
users.ForEach(x => { x.CreateTime = DateTime.Now.AddMonths(-1);
x.LastUpdateTime = DateTime.Now; });

