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 ?

sll
  • 61,540
  • 22
  • 104
  • 156
metalcam
  • 392
  • 2
  • 16

3 Answers3

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
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.

Dan Tao
  • 125,917
  • 54
  • 300
  • 447
0

You can do :

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

or

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