Joe
Joe

Reputation: 47619

Perform mutable updates in LINQ query?

I have a LINQ query where I want to return modified objects. If I were in an immutable Functional mood, I might do something copy-construtor-like, like this:

from widget in widgets select new widget { legs = widget.legs + 1, arms = widget.arms }

Sadly, I'm doing this on a mutable NHibernate entity object and I have to modify the original object. I'm looking for some syntax with a little anonymous method with side-effects, like:

from widget in widgets select { widget.legs += 1; return widget }

(with apologies to Scala syntax)

Now, I can perform this update outside the LINQ query, but I'd rather do it inline, if I can. Is it possible to insert void operations such as this in LINQ?

Upvotes: 3

Views: 2251

Answers (1)

Amy B
Amy B

Reputation: 110111

widgets
.ToList()
.Select(widget => 
{
  widget.legs +=1;
  return widget
})
.ToList()

ToList will enumerate (run) the query.

Edit, I've inserted a second ToList to allow Enumerable.Select to be used instead of Queryable.Select .

You indicate that you want NHibernate to run the code.... realize that query translators fulfill your request, but not your literal instructions.

from old in widgets
select new widget() {legs = old.legs + 1, arms = old.arms}

The query translator should send the projection into the database, rather than new'ing up 2 widgets.

Upvotes: 2

Related Questions