c# - update 2 fields using linq foreach -
can update 2 fields using linq foreach loop @ once? sample snippet : have userdata name, email, createtime, lastupdatetime fields. have reset createtime , lastupdatetime users.
to update using 2 calls below
users.foreach(x => x.createtime= datetime.now.addmonths(-1)); users.foreach(x => x.lastupdatetime = datetime.now);
instead can in single using linq foreach loop?
well start with, assuming list<t>.foreach
, isn't using linq. yes, can create lambda expression using statement body:
users.foreach(x => { x.createtime = datetime.now.addmonths(-1); x.lastupdatetime = datetime.now; });
however, may also want use 1 consistent time updates:
datetime updatetime = datetime.now; datetime createtime = updatetime.addmonths(-1); users.foreach(x => { x.createtime = createtime; x.lastupdatetime = updatetime; });
it's not clear why want achieve way though. suggest using 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
more thoughts on this.
Comments
Post a Comment