2

I've learned to manipulate Dynamic lambda expressions with the Expression class. However, the lambda expression used in a ForEach method (LINQ) seems a little different since it's an assign.

For exemple, doing this :

myList.ForEach(x => x.Status = "OK") ;

will update the Status property of each object in the myList list.

How to accomplish it using Expression object? I didn't find any method in Expression to set a property... Is it used only for retrieving properties values ?

1
  • What version of .NET are you using? V4 has it, while earlier versions don't. Commented Nov 25, 2011 at 16:36

3 Answers 3

6

Assignment does exist in expression trees (see Expression.Assign) as of .NET 4 (where it's used to support dynamic), but it's not supported by the C# compiler, which still only supports genuine "expressions" for lambda expression conversions to expression trees.

Sign up to request clarification or add additional context in comments.

Comments

1

I'm pretty sure Linq Expressions does not support assigning. I think you'd need to write a method with assignment in it and put that in the expression.

Update: Looks like assignment is supported as of .NET 4. See Jon Skeet's answer.

Comments

0

You can do :

myList.ForEach(x =>
{
    x.Status = "OK";
});

or

Action<YourType> oSetter = x =>
{
    x.Status = "OK";
});
myList.ForEach(oSetter);

2 Comments

You just said the same thing as the OP.
Oh sorry I misunderstood. Ok.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.