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
You can use the List's ForEach method:
List<MyObject> objects = new List<MyObject>();
// Populate list.
objects.ForEach(obj => {
obj.v1 += obj.dv1;
obj.v2 += obj.dv2;
});
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
foreach(var item in objects)
{
item.v1 += obj.dv1;
}
What you can do is pre-select, which elements from objects you want by something like this
foreach(var item in object.Where(o => o.v1 % 2 == 0))
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.
LINQ offers 'select' for transformation
list.Select( obj => new MyObject(obj.v1 + obj.dv1, obj.dv1, obj.v2 + obj.dv2, obj.dv2))
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.
I don't think this is typical task for linq, but if you want, you can do this:
List<MyClass> objects = GetMyClasses();
Func<Action<MyClas>s, bool> do = (action) => { action(); return true; }
(from o in objects
where do( o, b=> { b.v1 += b.dv1; b.v2 += b.dv2; } )
select o).ToArray();
Thanks for all answers. I was thinking linq can provide an elegant way, but you are right - foreach does the job just right.