views:

82

answers:

1

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?

+1  A: 
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.

David B
The compiler is saying that "A lambda expression with a statement body canot be converted to an expression tree" when I try to do that. Perhaps this would only work with LINQ to Objects? I want something that works with LINQ to NHibernate. Also: how would I do this with LINQ rather than lambda syntax?
Joe
Won't this have an identical result as his first example of "legs = widget.legs + 1"?
JustLoren
My first example was a copy-constructor to create a new object. David B's example would have updated the object in place (which is what I'm trying to achieve).
Joe
Expression trees in .NET 3.5/C# 3 do not support statements, which in turn means that can't be used to generate SQL. (This is also why VB doesn't have lambda statements.) This is supposed to be fixed in .NET 4/C# 4/VB 10.
Jonathan Allen
Thank you for that answer, Grauenwolf. That's explained a lot. And thanks David B. I'm accepting your answer because it was the closest solution possible!
Joe