I have a class
Class MyObject
{
decimal v1;
decimal dv1;
decimal v2;
decimal dv2;
}
and a
List<MyObject> ...
I need to process every element of the list by adding dv1 to v1 and dv2 to v2 Something like (pseudo-syntax):
myList.Transform(o=>o.v1+=o.dv1, o.v2+=o.dv2)
How can I do this (obvious my pseudo-syntax doesn't works)?
Thank you
LINQ offers 'select' for transformation
But be aware that the return value is a new list ; the elements of the original list are not modified. No Side effects/State mutation. If that is your goal, go for select ; else go with the for/for-each as others have suggested.
Thanks for all answers. I was thinking linq can provide an elegant way, but you are right - foreach does the job just right.
I don't think this is typical task for linq, but if you want, you can do this:
You can use the List's ForEach method:
LINQ is made to get a subset of a given enumeration or to create an enumeration with new types out of an list.
To manipulate a given list, LINQ is not the right tool to manipulate a given list. To do your task you should take a foreach loop like
What you can do is pre-select, which elements from objects you want by something like this
Like others mentioned you could self implement a
ForEach()
extension method, but there is a reason why it doesn't exist:Take a look at Erics Blog entry.